关闭Word文档时是否触发了VBA事件? [英] Is there a VBA event triggered when a Word document is closed?
问题描述
我试图将 Normal.dotm
用作类似于Excel中 Personal.xlsb
对象的宏存储对象.
I'm trying to use Normal.dotm
as a macro storage object analogous to the Personal.xlsb
object within Excel.
内置 <代码> Document_Close()事件似乎无法触发,除非它包含在特定文档的 ThisDocument
对象中.
I've also tried to use this Application_Quit()
event like so but to no avail:
Private Sub Application_Quit()
Msgbox "closing word"
End Sub
是否可以使用 Auto_Close()
等来监听单词应用程序在excel中的关闭状态?
Is it possible to listen for closing of the word application like it is in excel with Auto_Close()
, etc?
Public WithEvents App As Word.Application
普通模块模块1"
Dim X As New Class1
Sub Register_Event_Handler()
Set X.App = Word.Application
End Sub
Private Sub App_Quit()
MsgBox "closing word"
End Sub
推荐答案
有两种基本方法可以在关闭任何Word文档时进行捕获:
There are two basic ways to capture when any Word document closes:
- 在Normal.dotm的任何模块(或作为加载项加载的任何模板)中使用名为
AutoClose
的宏.这是WordBasic(Word 2.0和6.0)时代的老式"方式.
- Use a macro named
AutoClose
in any module of Normal.dotm (or any template loaded as an add-in). This is the "old-fashioned" way that comes from the WordBasic (Word 2.0 and 6.0) days.
请注意,如果任何其他文档(或模板)具有 AutoClose
,则它将覆盖运行更一般"级别的宏.换句话说,特定于文档(或模板)的代码具有优先权.
Note that if any other document (or template) has AutoClose
that this will over-ride the macro running a "more general" level. In other words, the document- (or template-) specific code takes priority.
Sub AutoClose()
MsgBox "The document " & ActiveDocument.FullName & " is closing."
End Sub
- 处理应用程序级事件.这需要一个类模块和一个普通"模块.事件代码在类模块中;初始化类的代码必须在普通"模块中.
此事件的名称是 DocumentBeforeClose
,并且可以被用户和代码取消(请参阅事件签名中的 Cancel
参数).
This event's name is DocumentBeforeClose
and can be cancelled, both by the user and by code (see the Cancel
parameter in the event signature).
与 AutoClose
相比,如果一个以上的文档或模板具有运行 all 的事件,则将触发-没有优先级或替代".
In contrast to AutoClose
, if more than one document or template has the event running all will fire - there is no priority or "override".
名为clsEvents的类模块
Public WithEvents app As Word.Application
Private Sub app_DocumentBeforeClose(ByVal Doc As Document, Cancel As Boolean)
MsgBox "The document " & Doc.FullName & " is being closed."
End Sub
模块
Public myEvents As New clsEvents
Public Sub StartEvents()
Set myEvents.app = Word.Application
End Sub
Public Sub EndEvents()
Set myEvents.app = Nothing
End Sub
请注意,如果同时存在两种类型的事件,则 AutoClose
会在之后 DocumentBeforeClose
触发.
Note that if both types of event are present the AutoClose
fires after DocumentBeforeClose
.
还请注意,有一个特定于文档的事件将仅针对该文档触发: Document_Close
.此事件必须必须位于该文档的 ThisDocument
类模块中.
Note also that there is a document-specific event that will fire only for that document: Document_Close
. This event must be in the ThisDocument
class module of that document.
Private Sub Document_Close()
End Sub
这篇关于关闭Word文档时是否触发了VBA事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!