【问题标题】:word 2003 vba bug? DocumentBeforePrint execute twice?word 2003 vba 错误? DocumentBeforePrint 执行两次?
【发布时间】:2018-11-09 02:49:17
【问题描述】:

这是 Word 2003 VBA 错误吗? DocumentBeforePrint 执行多次?

我参考

http://msdn.microsoft.com/en-us/library/office/aa211873(v=office.11).aspx

http://msdn.microsoft.com/en-us/library/office/aa211915(v=office.11).aspx

DocumentBeforeClose syntax

我用宏 DocumentBeforePrint 创建了一个 test.dot。

'ref http://msdn.microsoft.com/en-us/library/office/aa211915(v=office.11).aspx
Dim X As New EventClassModule

Sub Register_Event_Handler()
Set X.appWord = Word.Application
End Sub

Private Sub Document_New()
   Call Register_Event_Handler
End Sub

Private Sub Document_Open()
   Call Register_Event_Handler
End Sub


'ref http://msdn.microsoft.com/en-us/library/office/aa211873(v=office.11).aspx

Public WithEvents appWord As Word.Application

Private Sub appWord_DocumentBeforePrint _
    (ByVal Doc As Document, _
    Cancel As Boolean)

    MsgBox "WORKING!"
End Sub

当我按下 Ctrl+P 时,宏会执行。

有一个错误。当我双击 test.dot 生成两个 word 文件(a.doc/b.doc)时。

按Ctrl+P,DocumentBeforePrint会执行两次

如果我生成3个word文件,按Ctrl+P,宏会执行3次。

怎么了?我只想执行一次。

【问题讨论】:

  • 您没有提供足够准确的信息:我假设您提供给我们的代码不都在同一个模块中?请将其分开,并指出各个程序位于哪些模块中。
  • 我将测试文件上传到谷歌驱动器。drive.google.com/open?id=1aCwSQY4TCWWsU73fLVuNdloy22H3XW-m
  • 我不会下载您包含宏的文档。请使用edit 链接修改您的原始问题,并提供有关各种程序存储在哪些模块中的信息 - 它们肯定不是都在一个模块中?
  • 看看我编辑的答案,你就会明白我为什么问我原来的问题。

标签: vba ms-word


【解决方案1】:

您似乎已将除打印代码之外的所有代码都放在了ThisDocument 代码模块中。这是不正确的。因为您将 ^Dim X 设置为 NewEventClassModuleinThisDocument`,它本身就是一个代表每个文档的类模块,因此创建了多个实例。在“普通模块”中声明它不会导致此问题。

你需要三个模块:

“普通”模块:

Dim X As New EventClassModule

Sub Register_Event_Handler()
  Set X.appWord = Word.Application
End Sub

“本文档”模块:

Private Sub Document_New()
   Register_Event_Handler
End Sub

Private Sub Document_Open()
   Register_Event_Handler
End Sub

“事件类模块”

Public WithEvents appWord As Word.Application

Private Sub appWord_DocumentBeforePrint _
    (ByVal Doc As Document, _
    Cancel As Boolean)

    MsgBox "WORKING!"
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多