Change value of Word MailMerge field using VBA

David picture David · Apr 5, 2013 · Viewed 17.5k times · Source

I have a document with MailMerge fields, however I do not want to use the whole datasource->mailmerge idea. Instead I am presenting a UserForm on Autonew() and asking the user to type the data into the fields.

The reason is because this document is to "merged" with one row of data so it is a waste of time asking the user to do the whole data source thing for one row.

I have a working solution using DocVariables which I'm sure most people will say is the correct way to do it, however this client likes the idea of "seeing" the mailmerge variable (such as <<1>>) in the source document. They know they can use Alt-F9 to display codes to see the DocVariables, but they insist on wanting to use MergeFields.

Using DocVariables I do it using the following. This works so I know I have the right idea and that the rest of my code works fine.

ActiveDocument.Variables("varSurame").Value = .txtSurname

However, I cannot workout how to do the same thing with merge fields. I want to do something like the below (but there is no "value" property to set).

ActiveDocument.MailMerge.Fields("Surname").value = .txtSurname

The .text property is readonly so I cannot use that.

The following renders "Bookmark not defined" errors.

ActiveDocument.MailMerge.Fields("Surname").Code.Text = .txtSurname

Any ideas on how I can programmatically change the value of a mail merge field without using a datasource.

Answer

user1379931 picture user1379931 · Apr 16, 2013

Something like:

Dim f as Word.Field

For Each f in ActiveDocument.Fields

  If f.Type = wdFieldMergeField Then

    ' you will either need to extract the name of the field from f.code here
    ' (roughly speaking, you should expect to find
    ' MERGEFIELD<white space><optional double quote>fieldname<optional double quote><white space><possible switches>
    ' or you could iterate through a list of field names and use instr to look for each name
    ' then

    f.Result.Text = "the text you want"
  End If
Next ' f