Share via


使用事件搭配 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

初始化宣告的物件

您必須使用 Application 物件,在類別模組中連接宣告的物件 (本範例為 App),此程序才能執行。 您可以從任何模組使用下列程式碼以執行此作業。

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 支援與意見反應