I want to update a word field content using VBA. I already have a code that works, but I have to refer to the field's index instead of field's name, which I would prefer.
The code I have is as follows:
Sub UpdateField()
Dim myString As String
myString = "asdf"
ActiveDocument.Fields(1).Result.Text = myString
End Sub
Suppose that the field's name is MyField1. The following code will not work (I get the Run-time error '13': Type mismatch'.
Sub UpdateField()
Dim myString As String
myString = "asdf"
ActiveDocument.Fields("MyField1").Result.Text = myString
End Sub
I create my word fields from File Menu > Informations > Advanced Properties > Custom Tab.
So, how to refer to the field's name when we want to update its content?
These are
DocPropertyfields. If you press Alt+F9 you'll see the field codes.A
DocPropertyfield references (links to) a Document Property. The Document Property has the name, but this does not "name" the field. Nor is it possible to update aDocPropertyfield directly since it links to the Document Property. It might be possible to make it temporarily display something else, but this will be lost any time the field is updated.In order to update a
DocPropertyfield it's necessary to update the underlying Document Property. For example