Search code examples
vb.netms-wordfieldmailmerge

Changing the value of a Word 2007 document field using VB.Net


I have a word document with a number of fields scattered around the text. The fields were created using insert > quick parts > field. Each field has a unique name.

I managed to open the document but I don't know how to reference a particular field so that I can put in my value.

I managed to iterate through the fields in the document using:

Dim flds As Word.Fields
Dim fld As Word.Field

flds = wrdDoc.Fields
For Each fld In flds
...
next

But the "fld" variable does not seem to have a "name" property and therefore I don't know how to reference a specific field.

I was hoping that there was something like:

flds("MyField1") = "blablabla"

But I can only put indexes (integers) in the brackets.

Any ideas about how I can go about reaching my goal?

Thanks


Solution

  • What kind of fields are they? I don't know if this will fit in your case, but if the fields look like this when shown (with ALT-F9):

    {DOCVARIABLE fieldname}

    then use this:

    wordDocument.Variables("fieldname").Value = "abc"
    wordDocument.Fields.Update
    

    This will work only on DOCVARIABLE-Fields. (Note in this case that the string passed to .Value may not be empty.)