Share via


MailMergeDataSourceValidate Event

Occurs when a user performs address verification by clicking Validate in the Mail Merge Recipients dialog box.

Private Sub*object_*MailMergeDataSourceValidate(ByVal Doc As Document, Handled As Boolean)

object An object of type Application declared with events in a class module. For information about using events with the Application object, see Using Events with the Application Object .

Doc The mail merge main document.

HandledTrue runs the accompanying validation code against the mail merge data source. False cancels the data source validation.

Remarks

If you don't have address verification software installed on your computer, the MailMergeDataSourceValidate event allows you to create simple filtering routines, such as looping through records to check the postal codes and removing any that are non-U.S. Non-U.S. users can filter out all U.S. postal codes by modifying the code sample below and using Microsoft Visual Basic commands to search for text or special characters.

Example

This example displays a message, asking if addresses in the data source should be validated. This example assumes that the postal codes are U.S. ZIP Codes and that you have declared an application variable called MailMergeApp in your general declarations and have set the variable equal to the Word Application object. (You could modify this example to filter for international postal codes or for U.S. ZIP codes that have an appended 4-digit locator code.)

Private Sub MailMergeApp_MailMergeDataSourceValidate(ByVal Doc As Document, _
        Handled As Boolean)

    Dim intCount As Integer

    Handled = True

    On Error Resume Next

    With Doc.MailMerge.DataSource

        'Set the active record equal to the first record in the data source
        .ActiveRecord = wdFirstRecord
        Do
            intCount = intCount + 1

            'Set the condition that field six must be greater than or
            'equal to five
            If Len(.DataFields(6).Value) < 5 Then

                'Exclude the record if field six is less than five digits
                .Included = False

                'Mark the record as containing an invalid address field
                .InvalidAddress = True

                'Specify the comment attached to the record explaining
                'why the record was excluded from the mail merge
                .InvalidComments = "The zip code for this record is " _
                    & "less than five digits. It will be removed " _
                    & "from the mail merge process."

            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

End Sub

Applies to | Application Object