VBA and Field Codes in MS Word
Using Visual Basic for Applications (VBA) to work with Word’s field codes can seem a bit tricky at first, compared to manual field code management. But the time savings that VBA code provides easily justifies the initial effort to write it.
When using VBA to manage Word’s field codes, you’ll want to implement these functions: adding field codes, deleting them, and navigating to them. The VBA program code in this article implements these functions.
Install the program code
Install the program as follows:
Open Word 2007 and enter the Visual Basic IDE (integrated development environment) by pressing alt-F11. In the Project window, select Normal, then create a new user form by selecting Insert>User Form.
Using one ListBox and two button controls from the control Toolbox, design a form that looks like the following figure. Be sure to create the Delete Field button before the Close button.
Tip: set the text for the button controls by right-clicking them, choosing Properties, then setting the Caption property to the appropriate text do "Delete Field" and "Close."
When you’ve finished designing the form’s appearance, install the program code to make the form work: double-click the form to enter the code window, and paste the following code into that window:
Private Sub CommandButton1_Click()
‘Delete a field and remove it from the listbox
ActiveDocument.Fields(ListBox1.ListIndex + 1).Delete
‘Delete from list
Private Sub CommandButton2_Click()
Private Sub ListBox1_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
Dim s As String
Dim i As Integer
‘Which item was double-clicked? Navigate to it
i = ListBox1.ListIndex
ActiveDocument.Fields(i + 1).Select
Private Sub UserForm_Initialize()
‘Load the list box with the field code text from each field code in the main document
Dim i As Integer
Dim s As String
For i = 1 To ActiveDocument.Fields.Count
s = ActiveDocument.Fields(i).Code
Use the Form
Double-click Normal>Microsoft Word Objects>ThisDocument in the Project window. Enter the following code in the code window:
Public Sub showFieldForm()
That subroutine lets us call up the user form from Word. Return to Word and create some field codes in a document. Try inserting these:
– Insert>Quick Parts> Field>Date&Time, with the Update Automatically option checked
– Insert>Quick Parts>Field>Author
– Insert>Quick Parts>Field>NumWords
Run the user form you created by pressing alt-F8 and double-clicking the macro showFieldForm in the macro list. When the user form appears, notice the items in its listbox: all the field codes you entered. Double click one or two to navigate to, then press Delete to delete them. Close the form to notice the deleted fields.
Creating Field Codes Programmatically
The previous exercise showed how to navigate and delete field codes from VBA, but how and when might you use VBA to create them? Consider this scenario:
You’re typing a letter that might go out to several different people, but you don’t want to trouble with the multi-step process of creating a mail merge. You can instead use field codes to display the letter’s addressee anywhere in the letter. When you change the addressee’s name, the field codes will automatically change to display it.
Enter the Field-Creation Program Code
This task will make use of both field codes and bookmarks. Start with the field code functionality first: re-enter the Visual Basic IDE by pressing alt-F11. Double-click Normal>Microsoft Word Objects>ThisDocument on the Properties window, and select a clear space to enter the following code into:
Public Sub insertLink()
Dim p, q, s As String
‘create the link field code text
p = ActiveDocument.FullName
q = Replace(p, "\", "\\") ‘Must escape filename backslashes
s = "link word.document.12 " & q & " bm \a \r"
Selection.Fields.Add Range:=Selection.Range, Text:=s
Return to Word and assign a shortcut key to the macro: click the round MS Office button, then Word Options>Customize, and then the Customize button next to Keyboard shortcut. In the Customize keyboard window, select the Macro category and the InsertLink Macro. Enter a shortcut like Alt-L, then close the window.
While you’re still in the Word Options window, select the option to display bookmarks: Choose Advanced, scroll down to the "Show document content" heading, and check the Show bookmark checkbox. Return to the main document.
Compose the letter in our letter-writing scenario. Start the letter with this greeting:
Dear Mr. Perkins:
Bookmark the addressee, Mr. Perkins: select the "Mr. Perkins" text, click Insert>Bookmark, then add the bookmark "bm" to the selected text. Close the window to return to Word, and resume the letter writing with the following text, being sure to follow the instructions to "press alt-L."
The Halibut was delicious. Thank you for taking the time to prepare it. You are truly one-of-a kind, [press alt-L]. Finding another like you would be an impossible task.
So long, [press alt-L], and thanks for all the fish.
When you’re done writing the letter, update its field codes by selecting the whole document and pressing F9. The field codes will display the text you bookmarked: Mr. Perkins. Change the addressee now: position the cursor just inside the left brace of the "Mr. Perkins" bookmark. Type in "Mrs. Tillman" (without quotes), and delete the extra text up to the closing brace.
Select the whole document and press ctrl-A once again to update the field codes, which should now show "Mrs. Tillman."
For further exploration
The code examples in this article showed you how to navigate to, delete and create field codes from Visual Basic for Applications. If your documents use field codes, you can now more ably manage them by applying and customizing the programming examples.
References: Microsoft Office Online: Word’s Field Codes