The Microsoft Word 2002 object model exposes new events that are fired during the different stages of a mail merge. You can use these events to take custom actions while a user is performing a mail merge in the Word user interface, or you can use these events during Automation to Word. This article describes the mail merge events and uses code to illustrate the event sequence and possible uses for these events.
The following table describes the mail merge events that Word fires when you perform a mail merge:
This event fires when the
Mail Merge Wizard state has changed, either programmatically or because the user has
selected to move to the next or previous step. You can use this event to
verify or validate user selections before you move
to the next step in the Wizard.
This event fires when the
mail merge data source is loaded. You can retrieve information about the
data source and the records it contains by using the DataSource
property of the document's MailMerge object.
This event fires when a merge is about to be
executed for a range of records. You can use a handler for this event to prompt the
user to confirm the merging
process or to stop the merge.
This event fires when a merge is about to
execute for an individual record. The record can be retrieved with Doc.MailMerge.DataSource and the record number by using
Doc.MailMerge.DataSource.ActiveRecord. With a handler for this
event, you may also choose to selectively cancel the merge for records.
This event fires after an
individual record is
successfully merged. You can use this event to journal which records are
merged in the document.
This event fires when all records have been
merged. This event does not fire if merging was cancelled or if it failed with an
error. You can use this event for notification of a successful mail merge.
This event fires when the Custom destination
button is clicked in Step 6 of the Mail Merge Wizard. You can set a
custom destination for the mail merge with the ShowSendtoCustom
property of the MailMerge object, and then handle this event to
perform custom processing for the mail merge, such as faxing the merge
In Word 2002, create a new document and save it as MailMergeDemo.doc.
This demonstration uses a Word macro and requires that macro security be set to either Medium or Low. On the Tools menu, point to Macro and then click Security. On the Security Level tab, select either Medium or Low security and click OK.
Press ALT+F11 to start the Visual Basic for Applications (VBA) Editor.
In the Project Explorer, locate and double-click the ThisDocument class in the VBA project of MailMergeDemo.doc. Add the following code to the ThisDocument class module:
Dim WithEvents wdapp As Application
Dim aSteps As Variant
Dim bCustomProcessing As Boolean
Dim sHTML As String
Private Declare Function ShellExecute Lib "shell32.dll" Alias _
"ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation As _
String, ByVal lpFile As String, ByVal lpParameters As String, _
ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long
Private Sub Document_Open()
'Get a reference to the Word application to handle mail merge events.
Set wdapp = Application
'Initialization of the demonstration.
aSteps = Array("Select document type", "Select starting document", "Select Recipients", _
"Write Your Letter", "Preview Your Letters", "Complete the Merge")
bCustomProcessing = False
Private Sub Document_Close()
Set wdapp = Nothing
Private Sub wdapp_MailMergeWizardStateChange(ByVal Doc As Document,
FromState As Long, ToState As Long, Handled As Boolean)
'Print information that indicates which step is currently shown.
Debug.Print "MailMergeWizardStateChange Event"
Debug.Print " - Starting Step " & ToState & " (" & aSteps(ToState - 1) & ")"
Private Sub wdapp_MailMergeDataSourceLoad(ByVal Doc As Document)
Dim oDS As MailMergeDataSource
Set oDS = Doc.MailMerge.DataSource
'Print information for the connected data source: the table name,
' the query string, and the list of fields in the data source.
Debug.Print "MailMergeDataSourceLoad Event"
Debug.Print " - Table : " & oDS.TableName
Debug.Print " - Query String: " & oDS.QueryString
Dim sFieldNames As String
For i = 1 To oDS.FieldNames.Count - 1
sFieldNames = sFieldNames & oDS.FieldNames(i) & ","
sFieldNames = sFieldNames & oDS.FieldNames(oDS.FieldNames.Count)
Debug.Print " - Field Names : " & sFieldNames
'This shows "Custom Processing" in Step 6 of the Mail Merge Wizard.
Doc.MailMerge.ShowSendToCustom = "Custom Processing"
Private Sub wdapp_MailMergeBeforeRecordMerge(ByVal Doc As Document, Cancel As Boolean)
Debug.Print "MailMergeBeforeRecordMerge Event"
Private Sub wdapp_MailMergeAfterRecordMerge(ByVal Doc As Document)
'Print information about which record was just processed for the merge.
Debug.Print "MailMergeAfterRecordMerge Event"
Debug.Print " - Processed Record # " & Doc.MailMerge.DataSource.ActiveRecord
Private Sub wdapp_MailMergeWizardSendToCustom(ByVal Doc As Document)
Debug.Print "MailMergeWizardSendToCustom Event"
'If the user selects "Custom Processing" in the last step of the mail
'merge wizard, this event is fired. In this event handler, a file dialog box
'prompts the user to select the name of a Web (.html) page. Then, the
'mail merge is executed to a new document. The rest of the custom
'processing is handled in the MailMergeAfterMerge event (which is
'triggered by the Execute method); in the MailMergeAfterMerge event,
'the new document is saved as HTML and displayed in the browser.
Dim oDialog As FileDialog, i As Integer
Set oDialog = Application.FileDialog(msoFileDialogSaveAs)
oDialog.Title = "Save Mail Merge Results As..."
For i = 1 To oDialog.Filters.Count
If oDialog.Filters(i).Description = "Web Page" Then
oDialog.FilterIndex = i
If oDialog.Show Then
Debug.Print " - Proceed with Custom Processing"
bCustomProcessing = True
sHTML = oDialog.SelectedItems(1)
Doc.MailMerge.Destination = wdSendToNewDocument
Debug.Print " - Custom Processing Cancelled"
Private Sub wdapp_MailMergeBeforeMerge(ByVal Doc As Document, ByVal
StartRecord As Long, ByVal EndRecord As Long, Cancel As Boolean)
Debug.Print "MailMergeBeforeMerge Event"
'Give the user a chance to cancel the mail merge. The choice (to proceed or
'to cancel) is printed.
Dim lResult As Long
lResult = MsgBox("You have selected to execute this mail merge. Are you sure?", vbYesNo)
If lResult = vbNo Then
Cancel = True
Debug.Print " - Mail Merge cancelled at your request"
Debug.Print " - Proceeding with Mail Merge"
Private Sub wdapp_MailMergeAfterMerge(ByVal Doc As Document, ByVal DocResult As Document)
'Print the count of records in the datasource and the name of the
'resulting document if the user selected to merge to a "new document".
Debug.Print "MailMergeAfterMerge Event"
Debug.Print " - Record Count: " & Doc.MailMerge.DataSource.RecordCount
If Not (DocResult Is Nothing) And Not (bCustomProcessing) Then
Debug.Print " - New Document: " & DocResult.Name
'For custom processing, save DocResult by using the HTML converter and
'then display the resulting HTML file in the browser.
If bCustomProcessing Then
DocResult.SaveAs sHTML, wdFormatHTML
ShellExecute 0, "Open", sHTML, "", "C:\", 1
Debug.Print " - Sent MailMerge results to the Browser"
Close the VBA Editor to return to the Word document.
Save MailMergeDemo.doc, close it, and then open it.
When the document opens, the Mail Merge Wizard Step 1 of 6 appears. Click Next: Starting Document in the wizard.
In Step 2 of 6, click Next: Select recipients.
In Step 3 of 6, click Browse.
The Select Data Source dialog box appears. In the File Name box, type the full path to the sample Northwind.mdb Access database (the default path is C:\Program Files\Microsoft Office\Office10\Samples\Northwind.mdb) and click Open. If you are prompted to confirm conversion, select OLE DB Database Files.
The Select Table dialog box appears. Select the Employees table and click OK.
The Mail Merge Recipients dialog box appears and lists nine employee records by default. Click OK to use all nine records for the mail merge.
In Step 3 of 6 of the Mail Merge Wizard, click Next: Write your letter.
While Step 4 of 6 is displayed, click the More Items button on the Mail Merge task pane. When the Insert Merge Fields dialog box appears, select Database Fields, then double-click several of the fields in the list to add them to the document and click OK. You can apply additional formatting or text to the document if you wish. In Step 4 of 6 in the Mail Merge Wizard, click Next: Preview your Letters.
In Step 5 of 6, click Next: Complete the Merge.
In Step 6 of 6, click any one of the options for the mail merge destination. You are prompted to confirm your choice. Click OK to proceed with the mail merge.
When the mail merge completes, press ALT+F11 to open the VBA Editor and examine the contents of the Immediate Window. The Immediate Window provides details on your choices in the Wizard and illustrates the order in which mail merge events occur. If you select Custom Processing in Step 6 of the Wizard, the contents of the Immediate Window resemble the following:
- Starting Step 1 (Select document type)
- Starting Step 2 (Select starting document)
- Starting Step 3 (Select Recipients)
- Table : SELECT * FROM [Employees]
- Query String: SELECT * FROM [Employees]
- Field Names : EmployeeID,LastName,FirstName,Title,TitleOfCourtesy,BirthDate,HireDate,
- Starting Step 4 (Write Your Letter)
- Starting Step 5 (Preview Your Letters)
- Starting Step 6 (Complete the Merge)
- Proceeding with Mail Merge
- Proceed with Custom Processing
- Processed Record # 1
- Processed Record # 2
- Processed Record # 3
- Processed Record # 4
- Processed Record # 5
- Processed Record # 6
- Processed Record # 7
- Processed Record # 8
- Processed Record # 9
- Record Count: 9
- Sent MailMerge results to the Browser