共用方式為


搭配 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. Select an event from the Procedure drop-down list box. An empty subroutine for the selected event is added to the class module.

  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 模板中的事件程序沒有全域範圍。 例如,正常模板中的事件程序僅在附加模板為正常模板時發生。 如果 Auto 巨集存在文件和附加範本中,就只會執行儲存在文件中的 Auto 巨集。 如果文件事件的事件程序存在文件和附加範本中,就會執行這兩個事件程序。

註解

關於為 應用程式 物件建立事件程序的資訊,請參見「 使用事件搭配應用程式物件」。

支援和意見反應

有關於 Office VBA 或這份文件的問題或意見反應嗎? 如需取得支援服務並提供意見反應的相關指導,請參閱 Office VBA 支援與意見反應