Archive for May, 2013

How to quickly create merge fields in Word

Wednesday, May 29th, 2013

As part of the development of our document merge tool, we work quite a bit with Microsoft Word templates. And naturally, our testing process requires us to create lots and lots of merge fields in Word. Now if you have worked with merge fields, you know that creating a merge field can be a bit tedious: You have to click Insert – Quick Parts – Field, scroll down in the Field names panel, click MergeField, and then type in the name of the field into the Field name box. And you have to do this for every field you need. That’s a lot of clicks, particularly when you want to create a good many merge fields.

Being the lazy folks we are, we wanted to speed up this process. So we created a little WordBasic macro to help us along. With this macro in place, when we want to create a new merge field, all we need to do is

  1. type in the name of the field into the Word document, just the same way we type any other text;
  2. select the field name text; and
  3. click a button.

Voila. The text is instantly converted into a merge field.

Below is the text of the macro.

Sub MakeMergeField()
Selection.Copy
Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:= _
"MERGEFIELD """ + Selection.Text + """ ", PreserveFormatting:=True
End Sub

And here are the steps for setting up a button for this macro in Word. Keep in mind that even though this list of steps seems a bit long, it’s actually quite straightfoward. This is a one-time setup, and you will have the button available anytime you want.

  1. Make the Developer tab available in your Word ribbon. See directions for doing this in Word 2007 and Word 2010.
  2. Click Developer – Macros. In the resulting popup, type MakeMergeField in the Macro name box, and click the Create button. The Visual Basic editor appears, with the macro outline already set up, and the cursor placed in the macro body.
  3. Copy the three lines in the body of the macro text above (between the Sub and End Sub lines) and paste them into the body of the macro.
  4. Close the Visual Basic editor.
  5. Create a new button for this macro in your quick-access toolbar.

Below is a short video demonstrating the steps. Enjoy! We hope you find this useful.