使用 Outlook Visual Basic for Applications 回應 Outlook 事件Using Outlook Visual Basic for Applications to Respond to Outlook Events

編寫事件程序(也稱為事件處理常式),以回應 Microsoft Outlook 中發生的事件。You write an event procedure (also known as an event handler) to respond to events that occur in Microsoft Outlook. 例如,您可以撰寫在 Outlook 啟動時,會自動將瀏覽器視窗放到最大的事件程序。For example, you can write an event procedure that automatically maximizes the explorer window when Outlook starts.

事件都會與特定物件有關聯。Events are associated with particular objects. Application物件是最上層的物件,永遠可用(也就是說,它不一定要建立)。The Application object is the topmost object, and is always available (that is, it does not have to be created). 您只要在左方清單中選取 Application,然後在右方清單中選取事件,就能在 ThisOutlookSession 模組視窗中新增 Application 事件程序。You can add an Application event procedure in the ThisOutlookSession module window simply by selecting Application in the left list and then selecting the event in the right list.

若是為 Application 物件以外的物件新增事件處理程式,需要幾個額外的步驟。Adding an event handler for objects other than the Application object requires a few additional steps.

首先,必須使用 WithEvents 關鍵字宣告變數,以識別要處理之事件的所屬物件。First, you must declare a variable using the WithEvents keyword to identify the object whose event you want to handle. 例如,若要宣告代表OutlookBarPane物件的變數,您可以將下列新增至程式碼模組。For example, to declare a variable representing the OutlookBarPane object, you would add the following to a code module.

Dim WithEvents myOlBar as Outlook.OutlookBarPane

然後,您可以myOlBar選取 [模組] 視窗的 [物件] 清單,然後選取 [程式] 清單中的事件。You can then select myOlBar in the Objects list of the module window and then select the event in the procedure list. [Visual Basic 編輯器] 會在模組視窗中新增該事件程序的範本。The Visual Basic Editor will then add the template for the event procedure to the module window. 接著再輸入要在事件發生時執行的程式碼。You can then type the code you want to run when the event occurs. 下列範例會顯示新增至OutlookBarPane物件BeforeNavigate事件程序的程式碼。The following example shows code added to the BeforeNavigate event procedure for the OutlookBarPane object.

Private Sub myOlBar_BeforeNavigate(ByVal Shortcut As OutlookBarShortcut, Cancel As Boolean) 
 If Shortcut.Name = "Notes" Then 
 MsgBox "You cannot open the Notes folder." 
 Cancel = True 
 End If 
End Sub

最後的步驟是新增程式碼,將物件變數設定為要處理之事件所屬的物件。The final step is to add code to set the object variable to the object whose event you want to handle. 此程式碼可以存在於巨集中,或者如下列範例所示,如果要在 Outlook 一執行時便處理該事件,即可將該程式碼放在 Startup 事件程序中。This code can exist in a macro, or if you want the event to be handled whenever Outlook runs, you can put it in the Startup event procedure, as in the following example.

Private Sub Application_Startup() 
 Set myOlBar = Application.ActiveExplorer.Panes(1) 
End Sub

支援和意見反應Support and feedback

有關於 Office VBA 或這份文件的問題或意見反應嗎?Have questions or feedback about Office VBA or this documentation? 如需取得支援服務並提供意見反應的相關指導,請參閱 Office VBA 支援與意見反應Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.