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

註解

如需建立 Application 物件之事件程序的相關資訊,請 參閱搭配 Application 物件使用事件

支援和意見反應

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