Help and Support

Word 2002 MailMerge event code demonstration

Article ID:285333
Last Review:March 8, 2005
Revision:3.0
This article was previously published under Q285333
On This Page

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.

Back to the top

MORE INFORMATION

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

Event Comments
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.

Back to the top

Demonstration

1.In Word 2002, create a new document and save it as MailMergeDemo.doc.
2.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.
3.Press ALT+F11 to start the Visual Basic for Applications (VBA) Editor.
4.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
    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 "MailMergeWizardStateChange Event"
    Debug.Print "   - Starting Step " & ToState & " (" & aSteps(ToState - 1) & ")"

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 "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 Sub

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

End Sub

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
   
End Sub

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
            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 Sub

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"
    Else
        Debug.Print "   - Proceeding with Mail Merge"
    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 "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 If

End Sub
					
5.Close the VBA Editor to return to the Word document.
6.Save MailMergeDemo.doc, close it, and then open it.
7.When the document opens, the Mail Merge Wizard Step 1 of 6 appears. Click Next: Starting Document in the wizard.
8.In Step 2 of 6, click Next: Select recipients.
9.In Step 3 of 6, click Browse.

a. 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.
b. The Select Table dialog box appears. Select the Employees table and click OK.
c. 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.
10.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.
11.In Step 5 of 6, click Next: Complete the Merge.
12.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.
13.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,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
					

Back to the top

REFERENCES

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 (http://support.microsoft.com/kb/285332/EN-US/) HOWTO: Automate Word 2002 with Visual Basic to Create a Mail Merge
289830 (http://support.microsoft.com/kb/289830/EN-US/) PRB: Prompted to Select Table with Word 2002 Mail Merge Code for Excel or Access Data Source

Back to the top


APPLIES TO
Microsoft Word 2002 Standard Edition

Back to the top

Keywords: 
kbinfo kbautomation KB285333

Back to the top

Article Translations

 

Related Support Centers

Other Support Options

  • Contact Microsoft
    Phone Numbers, Support Options and Pricing, Online Help, and more.
  • Customer Service
    For non-technical assistance with product purchases, subscriptions, online services, events, training courses, corporate sales, piracy issues, and more.
  • Newsgroups
    Pose a question to other users. Discussion groups and Forums about specific Microsoft products, technologies, and services.