Word 2002 MailMerge event code demonstration
This article was previously published under Q285333
This article has been archived. It is offered "as is" and will no longer be updated.
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:
|MailMergeWizardStateChange||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.|
|MailMergeDataSourceLoad||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.|
|MailMergeBeforeMerge||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.|
|MailMergeBeforeRecordMerge||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.|
|MailMergeAfterRecordMerge||This event fires after an individual record is successfully merged. You can use this event to journal which records are merged in the document.|
|MailMergeAfterMerge||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.|
|MailMergeWizardSendToCustom||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 results.|
- 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 ApplicationDim aSteps As VariantDim bCustomProcessing As BooleanDim sHTML As StringPrivate 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 LongPrivate 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 ThisDocument.MailMerge.ShowWizard 1 End SubPrivate Sub Document_Close() Set wdapp = NothingEnd SubPrivate 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) & ")"End SubPrivate 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) & "," Next 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" End SubPrivate Sub wdapp_MailMergeBeforeRecordMerge(ByVal Doc As Document, Cancel As Boolean) Debug.Print "MailMergeBeforeRecordMerge Event"End SubPrivate 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 End SubPrivate 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 Exit For End If Next If oDialog.Show Then Debug.Print " - Proceed with Custom Processing" bCustomProcessing = True sHTML = oDialog.SelectedItems(1) Doc.MailMerge.Destination = wdSendToNewDocument Doc.MailMerge.Execute Else Debug.Print " - Custom Processing Cancelled" End If End SubPrivate 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" Else Debug.Print " - Proceeding with Mail Merge" End IfEnd SubPrivate 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 End If '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 DocResult.Close False ShellExecute 0, "Open", sHTML, "", "C:\", 1 Debug.Print " - Sent MailMerge results to the Browser" End IfEnd Sub
- 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.
- 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:
MailMergeWizardStateChange Event - Starting Step 1 (Select document type)MailMergeWizardStateChange Event - Starting Step 2 (Select starting document)MailMergeWizardStateChange Event - Starting Step 3 (Select Recipients)MailMergeDataSourceLoad Event - Table : SELECT * FROM [Employees] - Query String: SELECT * FROM [Employees] - Field Names : EmployeeID,LastName,FirstName,Title,TitleOfCourtesy,BirthDate,HireDate, Address,City,Region,PostalCode,Country,HomePhone,Extension,Photo, Notes,ReportsToMailMergeWizardStateChange Event - Starting Step 4 (Write Your Letter)MailMergeWizardStateChange Event - Starting Step 5 (Preview Your Letters)MailMergeWizardStateChange Event - Starting Step 6 (Complete the Merge)MailMergeBeforeMerge Event - Proceeding with Mail MergeMailMergeWizardSendToCustom Event - Proceed with Custom ProcessingMailMergeBeforeRecordMerge EventMailMergeAfterRecordMerge Event - Processed Record # 1MailMergeBeforeRecordMerge EventMailMergeAfterRecordMerge Event - Processed Record # 2MailMergeBeforeRecordMerge EventMailMergeAfterRecordMerge Event - Processed Record # 3MailMergeBeforeRecordMerge EventMailMergeAfterRecordMerge Event - Processed Record # 4MailMergeBeforeRecordMerge EventMailMergeAfterRecordMerge Event - Processed Record # 5MailMergeBeforeRecordMerge EventMailMergeAfterRecordMerge Event - Processed Record # 6MailMergeBeforeRecordMerge EventMailMergeAfterRecordMerge Event - Processed Record # 7MailMergeBeforeRecordMerge EventMailMergeAfterRecordMerge Event - Processed Record # 8MailMergeBeforeRecordMerge EventMailMergeAfterRecordMerge Event - Processed Record # 9MailMergeAfterMerge Event - Record Count: 9 - Sent MailMerge results to the Browser
For additional information on using Automation to Microsoft Word for mail merge, click the article numbers below to view the articles in the Microsoft Knowledge Base:
285332 HOWTO: Automate Word 2002 with Visual Basic to Create a Mail Merge
289830 PRB: Prompted to Select Table with Word 2002 Mail Merge Code for Excel or Access Data Source
Merging MailMerge Mail Merge Events Word Automate Automation Automating prb inf
Article ID: 285333 - Last Review: 12/05/2015 23:52:32 - Revision: 3.1
Microsoft Word 2002
- kbnosurvey kbarchive kbautomation kbinfo KB285333