1

我知道 Word 中的 VBA 有一系列事件处理程序可以在文档中发生特定事件时触发事件,但我一辈子都无法让它们中的任何一个工作。

我需要更新邮件合并的每条记录上的一个字段,但我无法让它运行。

这是我目前所拥有的:

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

谁能告诉我a)它需要去哪里和b)它可能需要包含什么才能使其实际运行?

如果我手动运行子例程,它会在活动 MailMerge 记录上按预期工作。

4

2 回答 2

0

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

于 2014-05-28T01:04:19.587 回答
0

为 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
于 2016-01-14T02:18:41.460 回答