1
votes

I get that VBA in Word has a range of Event Handlers to trigger things when specific events occur in the document, but I cannot for the life of me get any of them to work at all.

I need to update a field on each record of a mail merge, but I cannot get it to run.

Here's what I have at the moment:

Private Sub Document_MailMergeRecordMerge()
    ActiveDocument.Variables("SuperV").Value = ActiveDocument.MailMerge.DataSource.DataFields("Supervisor").Value
End Sub

Can anyone tell me a) where this needs to go and b) what it might need to contain to make it actually run?

If I run the subroutine manually, it works as expected on the active MailMerge record.

2
Just wrote a whole answer over half an hour and realized there was a way easier way. Updating now.hammus

2 Answers

0
votes

Its not surprising you're having difficulty with this one. In order to access the event you need (which is the MailMergeBeforeRecordMerge Event), you need access to the Application Object.

This is relatively easy to do:

'declare global Application reference
Dim WithEvents wdApp As Application

'set the reference somewhere (I've used Document_Open, but you can use whatever you want)

Private Sub Document_Open()

    'Get a reference to the Word application to handle mail merge events.
    Set wdApp = Application
End Sub

Private Sub wdApp_MailMergeBeforeRecordMerge(ByVal doc As Document)
    Debug.Print ("MailMergeBeforeRecordMerge")

End Sub

'clean up
Private Sub Document_Close()
    wdApp = Nothing
End Sub

A couple of good examples are in the old MS docs fr Word 2002 (they still word in 2013): Word 2002 MailMerge event code demonstration

0
votes

Complete working example updated for Word 2016

'declare global Application reference
Dim WithEvents wdApp As Application
Private Sub Document_Open()
    Debug.Print ("Document_Open")
    'Get a reference to the Word application to handle mail merge events.
    Set wdApp = Application
End Sub

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

End Sub

Private Sub Document_Close()
    Debug.Print ("Document_Close")
    wdApp = Nothing
End Sub