I wanted a function in Word VBA that would add a Field to a Range’s Fields collection and automatically extend the Range to include the added field.
This mimics the behavior of the Range.InsertAfter function and similar functions.
It allows you to keep adding text, fields, and other items to a Word document sequentially.
The function I created is called InsertFieldAfter. Its parameters mimic the parameters to the Fields.Add function.
The Range you pass in is extended to include the newly added Field. The new Range is also returned as the function return value for convenience.
The text of the function and related support functions is below, followed by an example of how to use the function.
' Expand the Range to include the added field and return it. Public Function InsertFieldAfter( _ ByRef Range As Word.Range, _ ByVal FieldType As WdFieldType, _ ByVal Text As String, _ Optional ByVal PreserveFormatting As Boolean = False _ ) As Word.Range On Error GoTo handler Dim StartPos As Long, EndPos As Long StartPos = Range.Start Range.Collapse Direction:=wdCollapseEnd EndPos = Range.Fields.Add( _ Range:=Range, _ Type:=FieldType, _ Text:=Text, _ PreserveFormatting:=PreserveFormatting) _ .Result.End + 1 Range.SetRange StartPos, EndPos Set InsertFieldAfter = Range Exit Function handler: ' handle any run-time error here End Function
Here’s a code snippet showing an example of its use:
With myRange .InsertAfter "Here is a field: " InsertFieldAfter Range:=myRange, FieldType:=wdFieldEmpty, Text:="REF Field1" .InsertAfter vbCrLf & "Here is another field: " InsertFieldAfter Range:=myRange, FieldType:=wdFieldEmpty, Text:="REF Field2" .InsertAfter vbCrLf End With