Extending Mail Merge Features
Microsoft® Word 2002
Summary: Microsoft Word 2002 includes several new mail merge features and enhancements to existing features. This article explains how those changes affect the Word 10.0 Object Library. (8 printed pages)
Customizing the Mail Merge Wizard
Modifying and Displaying the Wizard
Displaying a Custom Button on the Wizard
Removing Data Source Records from a Mail Merge
Mapped Data Fields
Using Mail Merge Events
The Microsoft® Word 10.0 Object Library provides several new members especially valuable to developers creating custom mail merge solutions. There are new properties and methods that you can use to validate data and customize the wizard and new events that run before, during, and after a mail merge. In addition, you can map the fields in a data source to built-in fields in Word to improve your ability to switch data sources for a document. This article describes how you can use these new members and features to create powerful custom mail merge solutions.
The Mail Merge Helper has been used in Word for several versions to guide users through the mail merge process. In Word 2002, the Mail Merge Wizard replaces the Mail Merge Helper, simplifying the mail merge process with clearer terminology and additional features. There are six steps in the Mail Merge Wizard, and you can customize most of the wizard's steps.
Using the ShowWizard method, you can specify steps to include or exclude from the wizard. When you use the ShowWizard method to remove a step in the wizard, the remaining steps are renumbered in the user interface. For example, if you use the ShowWizard method to remove step three (Select recipients), then step four (Write your letter) becomes step three, step five (Preview your letters) becomes step four, and step six (Complete the merge) becomes step five.
The WizardState property lets you determine whether the wizard is active or not. If the WizardState property returns zero, then the wizard is closed. However, if the wizard hasn't been opened in a document, calling the WizardState property will return a trappable error although the value is still zero.
The following function displays the Mail Merge Wizard for the specified document. If no arguments are given for the optional parameters, Word includes all steps in the wizard and displays step one as the initial step.
Function ShowMailMergeWizard(ByRef objDocument As Document, _ Optional ByVal intFirstStep As Integer = 1, _ Optional ByVal blnSelectDocType As Boolean = True, _ Optional ByVal blnSelectStartingDoc As Boolean = True, _ Optional ByVal blnSelectRecipients As Boolean = True, _ Optional ByVal blnWriteDoc As Boolean = True, _ Optional ByVal blnPreviewDoc As Boolean = True, _ Optional ByVal blnCompleteMerge As Boolean = True) As Boolean On Error Resume Next Const WIZARD_NOT_OPEN As Integer = 0 With objDocument.MailMerge If .WizardState = WIZARD_NOT_OPEN Then .ShowWizard InitialState:=intFirstStep, _ ShowDocumentStep:= blnSelectDocType, _ ShowTemplateStep:= blnSelectStartingDoc, _ ShowDataStep:= blnSelectRecipients, _ ShowWriteStep:= blnWriteDoc, _ ShowPreviewStep:= blnPreviewDoc, _ ShowMergeStep:= blnCompleteMerge ShowMailMergeWizard = True Else 'Indicates the wizard is already open and no changes 'are made. ShowMailMergeWizard = False End If End With End Function
You can use the following line to call the above function. This function call specifies the active document as the mail merge document, shows the Select starting document step as the first step in the wizard, and removes the Select document type and Preview document steps.
Call ShowMailMergeWizard(objDocument:=ActiveDocument, _ intFirstStep:=2, blnSelectDocType:=False, _ blnPreviewDoc:=False)
The On Error Resume Next statement in the ShowMailMergeWizard function above allows the code to run although the wizard may have never been opened in the specified document. If the wizard is closed or has never been opened in a document, the code includes or excludes the specified steps from the wizard, renumbers the mail merge wizard steps accordingly, and displays the wizard in the step indicated in the InitialState parameter of the ShowWizard method.
Note If the wizard has never been opened for a document, running this function against it will turn it into a mail merge document.
In addition to removing steps from the wizard, you can also add a button to the Complete the merge step in the wizard. The ShowSendToCustom property allows you to display a button with a custom caption on the Wizard's Complete the merge step. When a user clicks the custom button, the MailMergeWizardSendToCustom event is called. Note that if you remove the Complete the merge step from the wizard, you would need to provide your users with an alternate means of completing the mail merge process.
The MailMergeWizardStateChange event is called when a user moves from one step in the wizard to another. Note that although the ShowWizard method allows you to remove steps from the wizard and renumbers the steps, the MailMergeWizardStateChange event recognizes step one as step one regardless of whether you removed the first step from the wizard.
Using the new mail merge validation properties and methods, you can validate the records in your mail merge data source and exclude any that don't match your validation criteria. For instance, you can set the Included property of the MailMergeDataSource object to False to exclude a record.
You use the InvalidAddress property to mark a record as having an invalid address field and the InvalidComments property to enter a string explaining why an address is invalid or why a record has been excluded from the mail merge process. The InvalidAddress and InvalidComments properties are not available in Word's user interface but can be used by add-ins to associate validation information with each record for their own user interface.
If you want to exclude all records in a data source at the same time, set the Included argument of the SetAllIncludedFlags method to False. The SetAllErrorFlags method allows you to set the InvalidAddress property and InvalidComments property for all of the records in the data source at the same time.
The following function uses the Included, InvalidAddress, and InvalidComments properties to exclude any records in an attached data source where the specified field has entries with less than a specified number of digits. This function was designed to remove from the merge process all records with postal codes of less than five digits.
The function also uses the new RecordCount property to determine the total number of records in the data source. In most cases this property will function properly; however there may be times, especially with large databases, when Word is unable to read the total number of records. To resolve this problem, use On Error Resume Next to force the code to continue running and complete normally. If the specified document is not a mail merge document, the function returns False. Otherwise, it returns True after it validates all data in the attached data source.
Function CheckRecords(ByRef objDocument As Document, _ ByVal intPostalField As Integer, _ ByVal intFieldLength As Integer, _ ByVal strRemove As String) As Boolean Dim intCount As Integer On Error Resume Next If objDocument.MailMerge.MainDocumentType = wdNotAMergeDocument Then MsgBox "Your main document is not a mail merge document." CheckRecords = False Else With objDocument.MailMerge.DataSource 'Set the active record equal to the first included record 'in the data source. .ActiveRecord = wdFirstRecord Do intCount = intCount + 1 'Set the condition that the specified field must be 'greater than or equal to the specified length. If Len(.DataFields(intPostalField).Value) < _ intFieldLength Then 'Exclude the record if the specified field is 'is less than the specified character length. .Included = False 'Mark record as containing an invalid address field. .InvalidAddress = True 'Attach a comment to the record explaining why the 'record was excluded from the mail merge. .InvalidComments = strRemove End If 'Move the record to the next record in the data source. .ActiveRecord = wdNextRecord 'End the loop when the counter variable equals the 'number of records in the data source. Loop Until intCount = .RecordCount End With CheckRecords = True End If End Function
The following example uses the above function to remove all records where the sixth field is less than five digits. If the CheckRecords function returns True, the code displays a message for the user that data validation is complete; otherwise, it displays a message that the CheckRecords function was unable to validate the data in your data source.
Sub CallCheckRecords() If CheckRecords(objDocument:=ActiveDocument, intPostalField:=6, _ intFieldLength:=5, strRemove:="Postal code is too " & _ "short to be valid.") = True Then MsgBox "All invalid addresses have been " & _ "removed from your mail merge." Else MsgBox "Unable to validate the data in your data source." End If End Sub
In addition to new properties for data validation, there is the new MailMergeDataSourceValidate event. This event executes when a user clicks on the Validate button in the Mail Merge Recipients dialog box. Using this event and the above properties or a third-party validation application, you can provide data validation capabilities to your custom mail merge solutions.
Also new to Word 2002 are mapped data fields. These are built-in fields that represent commonly used field names, such as "First Name," "Last Name," and "Address." If a data source contains a "First Name" field (or a variation such as "Fname," "FirstName," or "First"), the data source field automatically maps to the corresponding built-in mapped data field in Word. This mapping allows you to use multiple data sources for the same mail merge document without making changes to the merge fields in the letter.
The MappedDataFields collection and MappedDataField object provide automatic mapping of the field names in a data source and built-in field names in Word. The Name property of the MappedDataField object returns the mapped data field name, and the DataFieldName property returns the data source field name. The DataFieldIndex property returns the index number of the field in the data source to which a built-in field is mapped.
You can manually map data fields to built-in mapped data fields using the DataFieldIndex property of the MappedDataField object and the Index property of the MailMergeFieldName object. The following example manually maps an array of built-in data fields to an array of field names in the data source.
Sub MapDataFields(ByRef objDocument As Document, _ ByRef wdBuiltInFields() As WdMappedDataFields, _ ByRef strDataFieldName() As String) Dim intCount As Integer With objDocument.MailMerge.DataSource For intCount = LBound(wdBuiltInFields) To UBound(wdBuiltInFields) .MappedDataFields(wdBuiltInFields(intCount)).DataFieldIndex = _ .FieldNames(strDataFieldName(intCount)).Index Next intCount End With End Sub
The following example uses the above function to map two mapped data fields to two fields in the attached data source.
Sub CallMapDataFields() Dim wdBuiltIn(0 To 1) As WdMappedDataFields Dim wdFieldNames(0 To 1) As String Dim intCount As Integer wdBuiltIn(0) = wdBusinessPhone wdFieldNames(0) = "Extension" wdBuiltIn(1) = wdHomePhone wdFieldNames(1) = "HomePhone" Call MapDataFields(objDocument:=ActiveDocument, _ wdBuiltInFields:=wdBuiltIn, _ strDataFieldName:=wdFieldNames) End Sub
Several new events provide support before, during, and after a mail merge. The following table describes these new events. For more information, refer to Microsoft Word Visual Basic® for Applications (VBA) Help.
|MailMergeDataSourceLoad||Occurs when connecting to a data source.|
|MailMergeBeforeMerge||Occurs prior to starting the mail merge process.|
|MailMergeBeforeRecordMerge||Occurs before merging each record in a data source.|
|MailMergeAfterRecordMerge||Occurs after merging each record in a data source.|
|MailMergeAfterMerge||Occurs after merging all of the records in a data source.|
Mail merge is a powerful feature in Word. With the new members of the Word 10.0 Object Library described in this article, you can develop your own custom mail merge solutions that take full advantage of this power.