打开更多文档时,Word VBA 应用程序事件会触发更多次
我有以下问题。我编写了简单的宏,在打印对话框之前显示 MsgBox。这是源代码:
Public WithEvents App As Application
Private Sub App_DocumentBeforePrint(ByVal Doc As Document, Cancel As Boolean)
MsgBox "aaaaa"
End Sub
Private Sub Document_New()
Set App = Application
End Sub
当我使用此宏从模板打开一个文档时,一切正常。但是当我同时从此模板打开两个文档时遇到问题。当我单击打印按钮时,MsgBox 出现两次。有什么想法吗?
编辑: 当我从该模板创建文档并创建另一个不基于该模板的新文档(这两个文档同时打开)并且我从该新的空文档进行打印时,会显示 MsgBox。这也是错误的吧?
I have the following problem. I wrote simple macro which shows MsgBox before print dialog. Here is source:
Public WithEvents App As Application
Private Sub App_DocumentBeforePrint(ByVal Doc As Document, Cancel As Boolean)
MsgBox "aaaaa"
End Sub
Private Sub Document_New()
Set App = Application
End Sub
When I open one document from template with this macro, everything is OK. But I have a problem when I open two documents from this template at same time. When I click to print button, MsgBox shown up twice. Any ideas?
Edit:
When I create document from this template and create another new document, which isnt't based on this template (both of this documents are opened at the same time) and I print from that new empty document, MsgBox shown up. This is also wrong right?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您已经创建了每次打印任何文档时触发的应用程序级事件。对于其中包含此代码的每个文档,它们都会被触发一次,因此每次打印文档时,无论正在打印的文档中是否包含该代码,您都会为每个打开的包含该代码的文档获取一次 msgbox。 。
因此,这些行为并没有错,尽管它们显然不是您想要的。
您应该将 Before_Print 事件放在模板的 ThisDocument 模块中。这样,该事件只会发生一次,并且仅当正在打印的文档中包含代码时才会发生。
You have created application-level events that fire every time any document is being printed. They are triggered once for every document that has this code in it, so every time you print a document you will get the msgbox once for every open document that has the code in it, whether or not the document that's printing has the code in it.
So, the behaviors aren't wrong, although clearly they are not what you want.
You should put the Before_Print event in the ThisDocument module of your template. That way the event will only happen once, and only when the document being printed has the code in it.
您可以在 App_DocumentBeforePrint 子中进行检查,以检查触发事件的应用程序对象的实例是否是包含活动文档的实例:
You could put a check in your App_DocumentBeforePrint sub to check whether the instance of the application object which is firing the event is the instance that contains the active document: