I am building a form in Word in which I am making parts variable by introducing fields. The only way I can keep from getting an error in generating a field is to declare it and give it a value from the VB editor within Word. What I would like to do is set these variables from an independant VB program and then save the new document to a variable location.
I can open and save OK, but I run into problems setting the fields. Once I set them, I can see that they are changed but they do not show up in the word document. This may be difficult to read, so I will explain the output from the below code.
I have a test document with one field called "testvar". If I run the below code, I first get a box with "Converted!" in it. This shows that the value for field 'testvar' did get changed. Then I see a box with "testvar", showing that the variable is named correctly and my syntax is ok in referencing it. The last box comes up with "testvar" as well, showing that it is the first variable and an alternate way of referencing. Here is where it goes wrong, at the last step the text box is filled with the original value set when I declared the field in Word itself.
So is there a update fields type of command? I know within Word I have to hit F9 to update fields. Thanks for any help.
Private Sub cmdReadClick()
Dim objWord As Word.Application
Dim objDoc As Word.Document
Dim nword As Long
Dim newstring As String
Set objWord = New Word.Application
Set objDoc = New Word.Document
Set objDoc = objWord.Documents.Open("F:\brian\test.doc")
objDoc.Variables("testvar").Value = "Converted!"
MsgBox (objDoc.Variables("testvar").Value)
MsgBox (objDoc.Variables("testvar").Name)
MsgBox (objDoc.Variables(1).Name)
For nword = 1 To objDoc.Words.Count
newstring = newstring & objDoc.Words(nword).Text
txtDisplay.Text = newstring
Next nword
objDoc.Close False
objWord.Quit False
End Sub
Enter your message below
Sign in or Join us (it's free).