Microsoft Office Tutorials and References
In Depth Information
Mail Merge: Creating a User-Friendly List of Fields
Note: The following code should be placed in the UserForm module of the UserForm
that will use it.
Option explicit¶
' * * * * *¶
'Executes first when a UserForm is shown the first time¶
Private Sub UserForm_Initialize()¶
'Generate the list of field names¶
'Variable declaration¶
Dim fld As Word.MailMergeDataField¶
With ActiveDocument.MailMerge¶
'Continue only if a merge document with linked data source¶
If .MainDocumentType = wdNotAMergeDocument Then Exit Sub¶
'Display the full path and name of the data source file ¶
'above the list¶
lblDatasource.Caption = .DataSource.Name¶
'Loop through all the merge fields¶
'in the data source, adding the name to the list¶
For Each fld In .DataSource.DataFields¶
Me.lstMergeFields.AddItem fld.Name¶
Next fld¶
End With¶
End Sub¶
' * * * * *¶
Private Sub UserForm_Activate()¶
'Only hide the form, without unloading it,¶
'so that time is not spent¶
'recreating the list each time it's shown¶
'Must catch whether the data source¶
'has been removed in the meantime.¶
'If so, and the form is shown again, close the form¶
If ActiveDocument.MailMerge.MainDocumentType = wdNotAMergeDocument
Then¶
Unload Me¶
Exit Sub¶
End If¶
End Sub¶
' * * * * *¶
Private Sub cmdClose_Click()¶
'Close the UserForm without losing the list¶
Unload Me¶
End Sub¶
' * * * * *¶
'Field can be inserted by clicking the button¶
Private Sub cmdInsertField_Click()¶
'Insert the selected entry¶
ActiveDocument.Fields.Add Range:=Selection.Range, _¶
Type:=wdFieldMergeField, Text:=lstMergeFields.Text¶
End Sub¶
Wrd
Search JabSto ::




Custom Search