Search code examples
vbams-wordword-field

How to refer to Word Field by name in VBA Code?


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?


Solution

  • These are DocProperty fields. If you press Alt+F9 you'll see the field codes.

    A DocProperty field 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 a DocProperty field 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 DocProperty field it's necessary to update the underlying Document Property. For example

    Sub EditDocPropUpdateDocPropertyField()
        Dim doc As Word.Document
        Dim prop As Office.DocumentProperty
        Dim propName As String
        Dim newPropValue As String
    
        Set doc = ActiveDocument
        propName = "MyField"
        newPropValue = "new value"
        Set prop = doc.CustomDocumentProperties(propName)
        prop.value = newPropValue
        doc.Fields.Update
    
    End Sub