Microsoft KB Archive/285333

= Word 2002 MailMerge event code demonstration =

Article ID: 285333

Article Last Modified on 3/8/2005

-

APPLIES TO


 * Microsoft Word 2002 Standard Edition

-



This article was previously published under Q285333



SUMMARY
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.



MORE INFORMATION
The following table describes the mail merge events that Word fires when you perform a mail merge:

Demonstration
 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 &quot;shell32.dll&quot; Alias _ &quot;ShellExecuteA&quot; (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(&quot;Select document type&quot;, &quot;Select starting document&quot;, &quot;Select Recipients&quot;, _                  &quot;Write Your Letter&quot;, &quot;Preview Your Letters&quot;, &quot;Complete the Merge&quot;) bCustomProcessing = False ThisDocument.MailMerge.ShowWizard 1 End Sub

Private Sub Document_Close Set wdapp = Nothing End Sub

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 &quot;MailMergeWizardStateChange Event&quot; Debug.Print &quot;  - Starting Step &quot; & ToState & &quot; (&quot; & aSteps(ToState - 1) & &quot;)&quot;

End Sub

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 &quot;MailMergeDataSourceLoad Event&quot; Debug.Print &quot;  - Table       : &quot; & oDS.TableName Debug.Print &quot;  - Query String: &quot; & oDS.QueryString Dim sFieldNames As String For i = 1 To oDS.FieldNames.Count - 1 sFieldNames = sFieldNames & oDS.FieldNames(i) & &quot;,&quot; Next sFieldNames = sFieldNames & oDS.FieldNames(oDS.FieldNames.Count) Debug.Print &quot;  - Field Names : &quot; & sFieldNames 'This shows &quot;Custom Processing&quot; in Step 6 of the Mail Merge Wizard. Doc.MailMerge.ShowSendToCustom = &quot;Custom Processing&quot; End Sub

Private Sub wdapp_MailMergeBeforeRecordMerge(ByVal Doc As Document, Cancel As Boolean) Debug.Print &quot;MailMergeBeforeRecordMerge Event&quot;

End Sub

Private Sub wdapp_MailMergeAfterRecordMerge(ByVal Doc As Document)

'Print information about which record was just processed for the merge. Debug.Print &quot;MailMergeAfterRecordMerge Event&quot; Debug.Print &quot;  - Processed Record # &quot; & Doc.MailMerge.DataSource.ActiveRecord End Sub

Private Sub wdapp_MailMergeWizardSendToCustom(ByVal Doc As Document)

Debug.Print &quot;MailMergeWizardSendToCustom Event&quot; 'If the user selects &quot;Custom Processing&quot; 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 = &quot;Save Mail Merge Results As...&quot; For i = 1 To oDialog.Filters.Count If oDialog.Filters(i).Description = &quot;Web Page&quot; Then oDialog.FilterIndex = i           Exit For End If   Next If oDialog.Show Then Debug.Print &quot;  - Proceed with Custom Processing&quot; bCustomProcessing = True sHTML = oDialog.SelectedItems(1) Doc.MailMerge.Destination = wdSendToNewDocument Doc.MailMerge.Execute Else Debug.Print &quot;  - Custom Processing Cancelled&quot; End If End Sub

Private Sub wdapp_MailMergeBeforeMerge(ByVal Doc As Document, ByVal   StartRecord As Long, ByVal EndRecord As Long, Cancel As Boolean)

Debug.Print &quot;MailMergeBeforeMerge Event&quot; '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(&quot;You have selected to execute this mail merge. Are you sure?&quot;, vbYesNo) If lResult = vbNo Then Cancel = True Debug.Print &quot;  - Mail Merge cancelled at your request&quot; Else Debug.Print &quot;  - Proceeding with Mail Merge&quot; End If

End Sub

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 &quot;new document&quot;. Debug.Print &quot;MailMergeAfterMerge Event&quot; Debug.Print &quot;  - Record Count: &quot; & Doc.MailMerge.DataSource.RecordCount If Not (DocResult Is Nothing) And Not (bCustomProcessing) Then Debug.Print &quot;  - New Document: &quot; & 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, &quot;Open&quot;, sHTML, &quot;&quot;, &quot;C:\&quot;, 1 Debug.Print &quot;  - Sent MailMerge results to the Browser&quot; End If

End 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.</li> In Step 2 of 6, click Next: Select recipients.</li> In Step 3 of 6, click Browse.

<ol style="list-style-type: lower-alpha;"> 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.</li> The Select Table dialog box appears. Select the Employees table and click OK.</li> 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.</li></ol>

In Step 3 of 6 of the Mail Merge Wizard, click Next: Write your letter.</li> 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.</li> In Step 5 of 6, click Next: Complete the Merge.</li> 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.</li>  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: <pre class="fixed_text">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,ReportsTo MailMergeWizardStateChange 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 Merge MailMergeWizardSendToCustom Event - Proceed with Custom Processing MailMergeBeforeRecordMerge Event MailMergeAfterRecordMerge Event - Processed Record # 1 MailMergeBeforeRecordMerge Event MailMergeAfterRecordMerge Event - Processed Record # 2 MailMergeBeforeRecordMerge Event MailMergeAfterRecordMerge Event - Processed Record # 3 MailMergeBeforeRecordMerge Event MailMergeAfterRecordMerge Event - Processed Record # 4 MailMergeBeforeRecordMerge Event MailMergeAfterRecordMerge Event - Processed Record # 5 MailMergeBeforeRecordMerge Event MailMergeAfterRecordMerge Event - Processed Record # 6 MailMergeBeforeRecordMerge Event MailMergeAfterRecordMerge Event - Processed Record # 7 MailMergeBeforeRecordMerge Event MailMergeAfterRecordMerge Event - Processed Record # 8 MailMergeBeforeRecordMerge Event MailMergeAfterRecordMerge Event - Processed Record # 9 MailMergeAfterMerge Event - Record Count: 9 - Sent MailMerge results to the Browser </li></ol>

<div class="references_section">