Implementing a MERGEFIELD Class

Visual Basic User's Guide > Using Microsoft Word Fields

The MS Word MergeField is the most commonly used field in MS Word and RTF documents. It enables template designers to add additional information to a text field, such as a specific text that should be displayed before or after the field text or the format of the text.

To handle these fields and functionality, this sample implements a class that gets and sets the parameters of the TXTextControl.FieldTypeData.

This MergeField gets a reference to the TXTextControl.FieldCurrent property to manipulated the proper field in TX Text Control. Additionally, a MergeField contains the following parameters that are implemented through it's properties:

If the TextBefore property of the MergeField is set, the Text property of this class manipulates the referenced field and it's text. Additionally, this new setting is saved in the TXTextControl.FieldTypeData property in the appropriate format.

After starting the sample, click on File / Load to load a sample document, which contains several merge fields. Set the input position inside an exsiting field, for sample <<COMPANY>>.

Open the implemented merge field dialog by choosing Edit... from the MergeField main menu.

Using this dialog, it is possible to manipulate all properties of the MergeField instance. Add some text that should be inserted after the field by checking the checkbox Text to be inserted after. Type some text in the appropriate text box and close the dialog by clicking OK.

Select Merge fields... from the Merge menu entry to merge all merge fields with database content.

In this process, the TXTextControl.FieldNext property is used to loop through all inserted fields to replace the text. The following code shows this loop:

[Visual Basic]
oID = TXTextControl1.FieldNext(oID, &H8000)
Do While oID > 0
  Dim newMergeField As New MergeField
  Set newMergeField.TextControl = TXTextControl1
  newMergeField.FieldID = oID
  For i = 0 To rs.Fields.Count - 1
    If StrConv(rs.Fields(i).Name, vbLowerCase) = StrConv(newMergeField.MergeFieldName, vbLowerCase) Then
      If rs(i).value <> "" Then
        newMergeField.Text = rs(i).value
      End If
    End If
  oID = TXTextControl1.FieldNext(oID, &H8000)