Item-Level Events
This content is no longer actively maintained. It is provided as is, for anyone who may still be using these technologies, with no warranties or claims of accuracy with regard to the most recent product version or service release.
Working with the event procedures exposed by Microsoft® Outlook® objects (other than the Application object) is identical to creating event procedures in the other Office applications. First, you must declare an object variable by using the WithEvents keyword in the ThisOutlookSession module (or in another class module) for each object you want to work with. Second, you must add the Microsoft® Visual Basic® for Applications (VBA) code to the event procedure that you want to run when the event occurs. Finally, you must initialize the object variables that you have created.
For example, the following VBA code illustrates how to create an object variable that represents the Outlook Bar in the ThisOutlookSession module:
Dim WithEvents obpOutlookBar As Outlook.OutlookBarPane
When you declare an object variable as shown in the previous example, the variable name appears in the Object drop-down list in the class module's Code window. When you select this variable from the Object list, you can select the object's available event procedures by using the Procedure drop-down list. For example, the OutlookBarPane object shown earlier exposes the BeforeGroupSwitch and BeforeNavigate events.
Private Sub opbOutlookBar_BeforeNavigate(ByVal Shortcut As OutlookBarShortcut, _
Cancel As Boolean)
If Shortcut.Name <> "Inbox" Then
Msgbox "Sorry, you only have permission to access the Inbox."
Cancel = True
End If
End Sub
Now you need to initialize the object variable. You can do this in two places: in the Application object's Startup event procedure, so that the variable is always available, or in a custom procedure you create for the purpose of initializing object variables. The following code shows how to initialize the object variable by using the Startup event procedure:
Private Sub Application_Startup()
Set opbOutlookBar = Application.ActiveExplorer.Panes("OutlookBar")
End Sub
To determine how to instantiate an object variable, search the Microsoft Outlook Visual Basic Reference Help index for the name of the object you want to work with. For example, the Help topic for the OutlookBarPane object shows that the object is a member of the Panes collection and also that you use the string "OutlookBar"
to identify the object within the collection.
Note You can get more information about the objects, methods, and properties in the Outlook object model by using Microsoft Outlook Visual Basic Reference Help.