Word 2010 VBA: add text to template without deleting everything below - vba

I have been writing a code to build a custom document for weekly reporting. I had it set to create a new doc, build the tables, format everything, insert a logo, etc., and I hit a wall when Word crashed every time I tried to resize the logo through VBA. It then occurred to me that I was doing this the wrong way anyway, and that I should build a template, have the code open that template, and then insert the changes directly into that document.
When I add text to the range I need, everything below is deleted. I have three lines of a header; the third line is variable and will change each week. Below that I have three tables, some cells of which will be updated each week. Right now I am just stuck at the third line of the document.
Here is an example of what I have. It is extremely short because I started anew and hit a dead end immediately.
Dim Template as Document
Set Template = ThisDocument
Dim InsertSpot as Range
Set InsertSpot = Template.Range(46)
InsertSpot.Text = "Hello"
When I run that, everything is deleted below "Hello".
I tried some different things, such as:
Set InsertSpot = Template.Range(46,50)
InsertSpot.InsertAfter "Hello"
That doesn't work; it just adds "Hello" to the first cell of the first table.
I feel silly being stuck at such an elementary part, but I honestly have no idea what to do here. Everything I looked at online talked about how to insert text at a bookmark without deleting the bookmark. I just want to enter text, period.
Any thoughts?

I found the answer. I did the following:
Dim Template as Document
Set Template = ThisDocument
Dim InsertSpot as Range
Set InsertSpot = Template.Range(46, 46)
InsertSpot.Text = "Hello"
I had to list both the starting AND the ending character so that the inserted text would not bleed over into the rest of the page. Hope I helped someone else who is having a similar problem. Unfortunately Word VBA is pretty lacking in support and clear explanations.

other alternatives can be
ThisDocument.Range(46).InsertBefore "Hello"
ThisDocument.Tables(1).Range.InsertBefore "Hello"
ThisDocument.Paragraphs(3).Range.InsertAfter "Hello"

Related

Use a Userform for MS Word to Input to Values in Form Fields

I am trying to automate a repetitive manual task for another department. They have a word template several pages long. They have to enter data several times each time they use it. Many of these are repetitive "fields". I thought about setting up custom form fields. But having them go through the navigation and know the field names to update them is not optimal. I found one solution to create a bookmark for each data input, and create links to that bookmark where it needs to be repeated - better but not optimal. I was hoping to create a userform where they can enter all the data and have it populate bookmarks, custom fields, to whatever.
I found a video that does this, but when I try the code, it does not update the bookmark. i created userform with Textbox1, and a CommandButton, and a bookmark in the document called MWDate. The code I am trying to get to work is:
Private Sub CommandButton1_Click()
Dim MWDate As Range
Set MWDate = ActiveDocument.Bookmarks("MWDate").Range
MWDate.Text = Me.TextBox1.Value
Me.Repaint
UserForm1.Hide
End Sub
This is a code example I grabbed and modified from the tutorial video. I don't know what the "Me." is. It does not populate the bookmark, which tells me it is not getting to the repaint line. Nor does it ever get to the hide line.
Anyone have a fix? Or a better way? Thanks for any help you can give.

Event change of table in Word

Private Sub Document_Change(ByVal Target As Range)
Set table = ActiveDocument.Tables(1)
If Not Intersect(table, Target) Is Nothing Then
Target.AutoFormat ApplyColor: Red
End If
End Sub
I have the following code, but it does not seem to work in VBA Word.
Can anyone help me out?
I suppose that you copied the code from Excel VBA and tried to rebuild it a bit.
There are a few differences between Excel and Word VBA.
Intersect does not exist in Word VBA.
DocumentChange event in Word works differently from what you would expect - It occurs when a new document is created, when an existing document is opened, or when another document is made the active document. (https://msdn.microsoft.com/en-us/library/office/ff822189.aspx)
If you want to make changes in red, you may do the following:
Record the wholeDocument in a static string.
When there is a change - record again in a new string.
Compare the strings and color the differences.
However, this is a bit tough, as far as word does not have Changeevent as we are expecting it (e.g. as in Excel). Thus, you should run the VBA code a few times automatically.

Trouble with Copying VBA Code

I've been working on an independent project for a client of mine. They wanted to produce a button that, upon the user-click, it would open up a user-form and have a variety of macro-related options to choose from: a drop-down list, checkbox, option select button, etc.
I created a test formula and submitted it to the client; they enjoyed it thoroughly and decided to sent me a file to 'copy & paste' my original code within their excel file.
Problem is; because I'm a tad bit inexperienced with VBA I've run into a problem where once I click the button - the user form doesn't show up.
Below is a Dropbox link of the original file I created and it's original code; as well as the file that I am trying to copy.
Any help would be all welcome and appreciated.
Link to dropbox: https://www.dropbox.com/sh/l1t37lz8uritrua/AAAdWPGvw0GDZ6hW4SwmbBdRa?dl=0
OriginalProject.xlsm has a form named honor_roll_form which contains 100 lines of code.
CopyOfOriginal.xlsm has a form named UserForm1 which contains no useful code.
I do not believe there is any method of directly copying user forms from one workbook to another. Instead
Within VB Editor of OriginalProject.xlsm, select honor_roll_form.
Click File then Export File and save the form on your desktop or where ever you like.
You will now have two files on your desktop; one with an extension of frm and one with an extension of frx.
Within VB Editor of CopyOfOriginal.xlsm, click File then Import file.
Import honor_roll_form.frm
When I try clicking button "Honor Roll", I get "Method or data member not found" for project1Box. I will investigate after dinner (18:57 here) unless you tell me you already know why I am getting this error.
Extra comments in response to request from OP
It is late here but I have started looking down sub execute_button_Click within the second CopyOfOriginal.xlsm. I will comment on what I see even if it is not directly relevant to the non-execution of the macro.
If you open the VB Editor and look on the left you will see the Project Explorer. Near the top you will see:
Microsoft Excel Objects
Sheet1 (Sheet1)
I have always found this confusing. The first “Sheet1” is Excel’s Id for the worksheet and cannot be changed. The second “Sheet1” is the default name for the worksheet which can be changed. You can write Sheet1.Range("A1") or Worksheets("Sheet1").Range("A1"). That is: you can reference a worksheet by its Id or its name. You have named a variable of type Worksheet as Sheet1. Using Excel’s names as variable names can lead to bizarre errors so it is important to avoid doing anything like this.
It is better to always use meaningful names. At the moment, you know what Sheet1 means but if you come back to this macro in six or twelve months will you remember. I would use a variable as you have but I would name it WshtCis208 or WshtVBAProg or something similar.
Set ID = Range(Sheet1.Cells(2, 1), Sheet1.Cells(52, 1)) could be written as:
With WshtCis208
Set ID = Range(.Cells(2, 1), .Cells(52, 1))
End With
Using With statements produces faster code and, almost always, code that it easier to read.
“52” is the current bottom row for this table. Will you amend the macro for them every time they add or remove a student? There are several techniques for finding the last row, none of which is perfect in every situation. The technique that is the most convenient most of the time is:
Const ColCis208Id as Long = 1
Const ColCis208MidTermExam as Long = 5
Dim RowCis208Last as Long
RowCis208Last = .Cells(.Rows.Count, ColCis208Id).End(xlUp).Row
At the moment, column 1 is the Id column. It is perhaps unlikely that the Id column will move but it is very likely that some of the others columns will move when some new column is identified as useful. Do you want to scan the code trying to decide which 5s refer to the MidtermExam column when a Project3 column is added?
Constants allow you to name literals that might change. It makes your code easier to read and saves so much pain when a value changes.
.Rows.Count gives the number of rows in a worksheet for the current version of Excel so .Cells(.Rows.Count, ColCis208Id) identifies the bottom cell of column 1. End(xlUp).Row says go up until you hit a cell with a value and returns its row number. It is the VBA equivalent of Ctrl+Up.
The next statement subjectCount = … fails because projectBox does not exist on the form. You have changed the captions but not the names.
As far as I can see the form fails to execute because you have started updating it but have not finished.

automating word 2010 to generate docs

the webapp was already done on office2007 and i need to convert it so it'll work in office2010.
i was able to convert the header generator part of the code but i have problem with the body of the doc itself. the code copy the data from a "data" doc and paste it into the generated doc.
appword.activewindow.activepane.view.seekview = 0
'set appsel1 = appword.activewindow.selection
set appsel1 = appword.window(filepath).selection -that is the original one
appdoc1.bookmarks("b1").select
appword.selection.insertafter("some text")
appsel1.endkey(6) -the code stops here
appword.selection.insertafter("some other text")
the iexplorer debuger says ERROR:appsel1 object required. and when i view its data using the iexplorer debugger its data is "empty" instead of "{...}"
can anyone tell me what i'm doing wrong
if you need more of the code tell me.
From MSDN
After this method is applied, the selection expands to include the new
text.
If you use this method with a selection that refers to an entire
paragraph, the text is inserted after the ending paragraph mark (the
text will appear at the beginning of the next paragraph). To insert
text at the end of a paragraph, determine the ending point and
subtract 1 from this location (the paragraph mark is one character).
However, if the selection ends with a paragraph mark that also happens
to be the end of the document, Microsoft Word inserts the text before
the final paragraph mark rather than creating a new paragraph at the
end of the document.
Also, if the selection is a bookmark, Word inserts the specified
text but does not extend the selection or the bookmark to include the
new text.
So I suspect that you still have no selected text.
I wonder if you can do a Selection Collapse(wdCollapseStart) but that's just a thought.

Make Word's automatic spell-checking pick up dictionary changes

In MS Word it's possible to add words to a custom dictionary so they're recognized. If a word is not recognized, Word automatically puts a red squiggly line underneath it. If you add that word to the custom dictionary, this line disappears. What I'd like to do is perform this process automatically via a macro. It appears that one has to manually open the dictionary file and write the new word, as there is no method on the Word Dictionary object to add words to a given dictionary. This is no problem, except that Word doesn't automatically pick up the new word and remove the red squiggly lines underneath the newly-added word. I've even tried clearing the custom dictionaries and adding them back in, but it doesn't seem to reload the dictionary until you manually run a spell check. Sample code for this follows:
Dim x As Dictionary
Dim fname As String
fname = "C:\Users\me\AppData\Roaming\Microsoft\UProof\md.dic"
' code to add word to dictionary goes here
With CustomDictionaries
.ClearAll
.Add fname
.ActiveCustomDictionary = CustomDictionaries.Item(fname)
End With
Is there any way to make Word recognize the newly added word(s) in a custom dictionary without running the interactive spell check? It does this silently if you manually add words, but I can't seem to replicate this behavior in VBA. I'd like the red lines to go away automatically just like they do when you manually add words.
I haven't exactly solved the problem, but I think I figured out a work around. You can get a collection of Range objects which represent spelling errors using ActiveDocument.SpellingErrors. I'm going to search this collection for text matching the word I've added to the dictionary, and then set .NoProofing = True on the object. This appears to make the red lines go away, and having added the new word to the dictionary will prevent them from coming back the next time I open the document. I haven't fully tested this approach, but it looks promising.
EDIT
This approach is flawed, as additional instances of the word which are entered during the same session will have the red squigglies underneath them because they haven't been explicitly ignored and the spell check isn't yet using the updated dictionary. If you just pull up the custom dictionary dialog manually and click OK, something happens in the background to re-read the dictionary. I just can't figure out how to do this in code.