strajano
strajano

Reputation: 69

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?

Upvotes: 3

Views: 9074

Answers (3)

Cleber Maicon Loch
Cleber Maicon Loch

Reputation: 1

Sample to set text to fields by field name:

ThisDocument.FormFields.Item("MyField1").Result = "hello"

Upvotes: 0

Cindy Meister
Cindy Meister

Reputation: 25663

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

Upvotes: 3

John Korchok
John Korchok

Reputation: 4913

In the VBE, the Object Browser is a great way to find out what's possible. When I find Word>Field and click on it, I see a list of the members of Field. Name is not in that list. This means that the field object does not have a Name property. That's why you get the error.

You can work around this. One way is to create a bookmark around the field in question. Then in code, find the bookmark by name, then find the field by index inside the bookmark range.

Upvotes: 1

Related Questions