Insert Footer Field Codes Programmatically
You can use Visual Basic for Applications to insert footer field codes programmatically. The following macro code gives an example of this. It creates a link (a type of field code) between the word that currently contains the insertion point, to the footer of the first section of your document. You might use such a macro to quickly insert a keyword from the main section of your document into the footer.
You can enter install and run this program by doing the following:
- Inside Word, press alt-F11 to bring up the Visual Basic Integrated Development Environment.
- In the Project pane, double click the ThisDocument icon for the document you want to install the macro in.
- Paste the following code into a blank space in the code window.
- Return to Word, and enter a few words in the document.
- Position the cursor in one of the words, then press alt-F8 to bring up the macro list.
- Double-click the macro named "mklink".
- The macro links the current word to the document's footer.
Dim w As Range
Dim p As String
Dim q As String
Dim s As String
' select current word
Set w = Selection.Range
ActiveDocument.Bookmarks.Add Range:=w, Name:="bm"
'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"
'Put field code in footer
.Footers(wdHeaderFooterPrimary).Range.Fields.Add Range:=.Footers(wdHeaderFooterPrimary).Range, Text:=s
Learn more about Word macros from this Bright Hub article.