使用 Document 对象的事件

Document 对象支持多个事件,使你能够响应文档的状态。 在名为“ThisDocument”的类模块中编写响应这些事件的过程。使用以下步骤创建事件过程。

  1. Under your Normal project or document project in the Project Explorer window, double-click ThisDocument. (In Folder view, ThisDocument is located in the Microsoft Word Objects folder.)

  2. Select Document from the Object drop-down list box.An empty subroutine for the New event is added to the class module.

  3. "过程" 下拉列表框中选择一个事件。 将在类模块中添加选定事件的一个空子例程。

  4. 添加要在事件发生时运行的 Visual Basic 指令。

下例显示了 Normal 工程中的一个 New 事件过程,它在新建一个基于 Normal 模板的文档时运行。

Private Sub Document_New() 
 MsgBox "New document was created" 
End Sub

下例显示了文档工程中的 Close 事件过程,该过程只在该文档关闭时运行。

Private Sub Document_Close() 
 MsgBox "Closing the document" 
End Sub

自动宏不同,Normal 模板中的事件过程没有全局范围。 例如,仅当附加的模板是 Normal 模板时,才会发生 Normal 模板中的事件过程。 如果文档和附加的模板中存在自动宏,则只会执行存储在文档中的自动宏。 如果文档事件的事件过程存在于文档及其附加的模板中,则将运行这两个事件过程。

备注

有关为 Application 对象创建事件过程的信息,请参阅 对 Application 对象使用事件

支持和反馈

有关于 Office VBA 或本文档的疑问或反馈? 请参阅 Office VBA 支持和反馈,获取有关如何接收支持和提供反馈的指南。