将事件与 Application 对象 (Word)

若要创建 Application 对象事件的事件处理器,需要完成下列三个步骤:

  1. 在类模块中声明一个对象变量以响应事件。

  2. 编写特定的事件过程。

  3. 在另一模块中初始化声明的对象。

声明对象变量

在您可以为 Application 对象事件编写过程之前,必须创建新的类模块并声明带有事件的 Application 类型的对象。 例如,假定已经创建了一个名为 EventClassModule 的新的类模块。 新的类模块包含以下代码。

Public WithEvents App As Word.Application

编写事件过程

After the new object has been declared with events, it appears in the Object drop-down list box in the class module, and you can write event procedures for the new object. (When you select the new object in the Object box, the valid events for that object are listed in the Procedure drop-down list box.) Select an event from the Procedure drop-down list box; an empty procedure is added to the class module.

Private Sub App_DocumentChange() 
 
End Sub

初始化声明的对象

在运行过程之前,必须将类模块中声明的对象(本示例中是 App)与 Application 对象连接起来。 您可以从任何模块中使用以下代码执行该操作。

Dim X As New EventClassModule 
Sub Register_Event_Handler() 
 Set X.App = Word.Application 
End Sub

运行 Register_Event_Handler 过程。 运行该过程后,类模块中的 App 对象指向 Microsoft Word Application 对象,当事件发生时,将运行类模块中的事件过程。

支持和反馈

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