【问题标题】:Event handlers in Word VBA - MailMergeRecordMergeWord VBA 中的事件处理程序 - MailMergeRecordMerge
【发布时间】:2023-03-10 15:17:01
【问题描述】:

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

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

这是我目前拥有的:

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

谁能告诉我a)它需要去哪里以及b)它可能需要包含什么才能使其真正运行?

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

【问题讨论】:

  • 半小时多才写了一个完整的答案,并意识到有一种更简单的方法。现在更新。

标签: vba events ms-word eventhandler


【解决方案1】:

难怪你在这方面遇到困难。为了访问您需要的事件(即MailMergeBeforeRecordMerge 事件),您需要访问应用程序对象。

这比较容易做到:

'declare global Application reference
Dim WithEvents wdApp As Application

'在某处设置引用(我使用过 Document_Open,但你可以使用任何你想要的)

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

Word 2002 的旧 MS 文档中有几个很好的例子(它们在 2013 年仍然是 word): Word 2002 MailMerge event code demonstration

【讨论】:

  • 嗯,我已经尝试过了,虽然它没有抛出任何调试错误,但实际上似乎并没有在 wdApp_MailMergeBeforeRecordMerge() 子程序中运行代码。我在其中插入了一个 msgbox("Run!") 以查看它是否正在运行例程,但它似乎根本没有在运行 - 我不知道为什么。
  • @bbk 你对此有进一步了解吗?我也没有运气
【解决方案2】:

针对 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

【讨论】:

猜你喜欢
  • 2022-10-06
  • 2020-05-09
  • 2017-10-15
  • 2019-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多