使用 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.