B

Project 1 (VbaProject.OTM)

E t3 Microsoft Outlook Objects

ThisOutlookSession E Forms $ 13 Modules !+■ Cj Class Modules

Startup

AduancedSearchCompk AduancetiSearchStoppe ItemSend

Itf APILogonComplete HewMai!

OptionsPagesAdd Quit

Reminder

Private Sub Application Orj Error Resume iiex 1 Instantiate object Set objNS = Applies Set colExpl = Appli Set collnsp = Appli Set obJExpl = Appli Set colInbox Items = Set colInboxFolders = objNS.GetDefau

Set eolDeletedltems = objNS. Get-Defau Set colDeletedltemsFolders = objNS.G

'Create gobjCDO Session object and 1 Set ¡jobjCDO = CreateObject ( "MAPI. Ses gobjCDO.Logon False, False

1 Items toolbar

Call CBOutlookltems(objExpl,CurrentF 'Shared Iteni3 toolbar

Figure 9.6 - Select an Application event from the Procedures drop-down list box to create an application-level event procedure.

Figure 9.6 - Select an Application event from the Procedures drop-down list box to create an application-level event procedure.

When You Must Use WithEvents to Declare the Outlook Application Object

If you are writing a COM Add-in that traps Outlook events, you must explicitly declare an Outlook Application object using the WithEvents keyword. COM Add-ins are beyond the scope of this chapter; they are discussed in depth in Chapter 14. The technique you should use to create child objects of the Application object, however, applies equally to COM Add-ins and Outlook VBA code. Many of the child objects of the Application object can also raise events. You might be wondering how you write event procedures for those child objects. The trick is to declare these objects using the WithEvents keyword and to instantiate those objects in the correct event procedures. Object-related events beget additional event-aware objects and their event procedures.

Using WithEvents for Child Objects

As discussed previously, all objects in the Outlook Object Model are child objects of the parent Application object. Not every Outlook object supports events. Consult the Object Browser in Outlook VBA or the Microsoft Outlook Visual Basic Reference Help to determine which Outlook objects raise events. The following table lists application-level events in Outlook 2002 and the objects that raise those events. The events and objects that are new to Outlook 2002 appear in bold. Note that certain events are cancelable, meaning that you can write code to roll back the event depending on the conditions you evaluate during event processing.

Object Event Cancelable

Application AdvancedSearchComplete AdvancedSearchStopped No

ItemSend No

MapiLogonComplete Yes

NewMail No

OptionsPagesAdd No

Quit No

Reminder No

Startup No

NameSpace OptionsPagesAdd No

Explorers NewExplorer No

Explorer Activate No

BeforeFolderSwitch Yes

BeforeltemCopy Yes

BeforeltemCut Yes

BeforeMaximize Yes

BeforeMinimize Yes

BeforeMove Yes

BeforeSize Yes

BeforeViewSwitch Yes

Close No

Deactivate No

FolderSwitch No

SelectionChange No

ViewSwitch No

SyncObject OnError No

Progress No

SyncEnd No

SyncStart No

OutlookBarPane BeforeGroupSwitch Yes

BeforeNavigate Yes

OutlookBarGroup GroupAdd Before No

GroupAdd Before Yes

GroupRemove Yes

OutlookBarShortcut ShortcutAdd Before No

ShortcutAdd Before Yes

ShortcutRemove Yes

Folders FolderAdd No

FolderChange No

FolderRemove No

Inspectors Newlnspector No

Inspector Activate No

BeforeMaximize Yes

BeforeMinimize Yes

BeforeMove Yes

BeforeSize Yes

Close No

Deactivate No

Object Event Cancelable

Items ItemAdd No

ItemChange No

ItemRemove No

Reminders BeforeReminderShow Yes

ReminderAdd No

ReminderChange No

ReminderFire No

ReminderRemove No

Snooze No

Views ViewAdd No

ViewRemove No

To raise events for these child objects, you should follow these coding practices:

® Dimension the object as a public object variable, and use the WithEvents keyword in a class module. If you're writing Outlook VBA code, declare the child object variables using WithEvents in ThisOutlookSession.

® Instantiate the child object variable in an appropriate event procedure, or use a Sub procedure in module-level code to instantiate object variables that raise events. For example, you should instantiate the NameSpace object and the Explorers and Inspectors collection objects in the Application Startup event so that the events supported by these objects will be available throughout the life of the application. The following code illustrates this technique:

'Place these declarations in ThisOutlookSession Public WithEvents objNS As Outlook.NameSpace

Publ

c

WithEvents

Publ

c

WithEvents

Publ

c

WithEvents

Publ

c

WithEvents

Publ

c

WithEvents

Publ

c

WithEvents

Publ

c

WithEvents

Publ

c

WithEvents

Publ

c

WithEvents

Private Sub Application_Startup() Set objNS = Application.GetNamespace("MAPI") Set colFolders = objNS.Folders Set colReminders = Application.Reminders Set colExpl = Application.Explorers Set collnsp = Application.Inspectors Set objExpl = Application.ActiveExplorer Set colViews = objExpl.CurrentFolder.Views Set collnboxltems = objNS.GetDefaultFolder(olFolderlnbox).Items

Set colDeletedltems = _ objNS.GetDefaultFolder(olFolderDeletedltems). Items End Sub

Where to Instantiate Child Objects Declared Using WithEvents

It's important to determine the correct event procedure when you create additional child objects. For example, if you want to raise events for an Explorer object, you can either set a reference to an Explorer object in the Application Startup event or you can use the NewExplorer event of the Explorers collection object. The NewExplorer event passes an Explorer object to the NewExplorer event procedure. Using the code example above, a reference is set to objExpl in the Application Startup event. This Explorer object refers to the ActiveExplorer object of the Application object when Outlook launches. Either users or code can cause multiple Explorer objects to display for a given Outlook Application object. If you want to trap events such as FolderSwitch or BeforeShortcutAdd for another instance of an Explorer, you must either create a new Explorer object that you can instantiate in the NewExplorer event or reuse the existing objExpl object and set objExpl to the Explorer object that you receive in the NewExplorer event. Many of the examples in the following section will discuss strategies and options for raising events on child objects of the application's parent object.

Observing Events in the Example VBAProject.otm

Because it writes a statement to the VBA Immediate window when an event procedure fires, the VBAProject.otm project accompanying this book lets you observe events for mostof the available events in the Outlook Object Model. Following the firing sequence of events in the Immediate window is an excellent way to learn about the new events in the Outlook Object Model. To observe event tracing in the VBA Immediate window, you must follow these steps:

To turn on event tracing in the VBAProject.otm example

1. Select Macro from the Tools menu.

2. Select Security from the Macro submenu.

3. On the Security Level page of the Security dialog box, click the Low option. If you click Medium, you will have to click Enable Macros in the Security Warning dialog box every time Outlook starts.

5. Press Alt+F11 to open the VBA Editor.

6. Select Projectl Properties from the Tools menu.

7. In the Conditional Compilation Arguments edit box on the General page of the Project 1 - Project Properties dialog box, enter conDebug = 1.

9. Press Alt+F11 to return to Outlook.

10. Select Exit And Log Off from the File menu.

11. Restart Outlook. Event tracing will be turned on, and you can observe the firing sequence of events in the VBA Immediate window.

Application Events

Application-I eve I events are most useful when you write code for an Outlook COM Add-in. You cannot respond to application-I eve I events in VBScript code behind an Outlook form. ItemSend

The ItemSend event occurs when an item is sent either because a user clicked the Send button on the item or because code causes an item to be sent. Typically the ApplicationJtemSend event occurs after the form-level ltem_Send event and before the form-level ltem_Write and ltem_Close events. You should apply user-interface elements such as alert and dialog boxes with care in the ItemSend event. If you use the Cancel argument to cancel sending the item and the item has already been sent from an open Inspector, the Inspector will remain in its previously displayed state. The item's Inspector will not close as it normally would when the Send button is clicked. The following example unobtrusively strips all attachments from outgoing mail messages:

Private Sub Application_ltemSend(ByVal Item As Object, Cancel As Boolean) Dim oAttach As Outlook.Attachment

If Item .Attachments. Count And Item.MessageClass = "IPM.Note" Then Do Until Item.Attachments.Count = 0 Set oAttach = Item.Attachments.Item(1) oAttach. Delete Loop End If End Sub

The example above assumes that you are writing code directly to the explicit Application object in VBA. If you are writing a COM Add-in or using an event handler to instantiate an Outlook Application object that has been declared using With Events, the name of the Application object will differ but the code will remain the same.

NewMail

The NewMail event occurs when an item arrives in the Inbox of the current logged-on user. The NewMail event will not occur if an item arrives in the mailbox of a user for whom the logged-on user has delegate permissions. NewMail is a generic event that notifies you that mail has arrived in the Inbox. Unlike the ItemSend event, it does not pass an Item object representing the item or items that have arrived in the Inbox. If you want to raise an event for the arrival of a specific item in a folder, you should declare an Items collection object using WithEvents. Assign the Items collection object to the Items property of the folder that you want to monitor, and then write an event procedure for the Item Add event of the Items collection object. If the Explorer window is minimized, the following NewMail example causes the Explorer window to display with a normal window state.

Private Sub Application_NewMail() Dim olExplorer As Outlook.Explorer Dim olFolder As Outlook.MAPIFolder Set olFolder = _

Application.GetNamespace(" MAP I"). Get Defa u It F ol de r(ol Fol der I n b ox) Set ol Explorer = Application .ActiveExplorer If olExplorer.WindowState = ol Minimized Then If ol Explorer. Current Folder <> olFolder Then ol Explorer. Current Fol der = olFolder End If olExplorer.WindowState = ol Normal Window ol Explorer. Display ol Explorer .Activate End If End Sub

OptionsPagesAdd

OptionsPagesAdd is the one event in the Outlook Object Model that appears at first examination to be misnamed. This event occurs after a user selects the Options command on the Tools menu of the Outlook Explorer and before the Tools Options dialog box actually displays. Consequently, you may prefer to think of the OptionsPagesAdd event as the BeforeOptionsPagesAdd event. From the perspective of the Application object, the OptionsPagesAdd event refers to the property pages of the Tools Options dialog box. You can use this event to add custom property pages to the Tools Options dialog box. Previous versions of Outlook required complex C++ coding to add property pages to this dialog box. See Chapter 14 for a complete example of how to create an ActiveX control and use this control as a property page that stores and retrieves settings from the Windows registry.

Figure 9-7 illustrates a property page with the caption Sample Page that has been added to the Tools Options dialog box. Be aware that creating an Outlook property page requires a complete understanding of how to create ActiveX controls and how to read and save registry values. Typically, you will want to use the Windows registry to preserve user settings on controls in your property page.

The Programmatic ID of the ActiveX control that contains the controls on the property page is PPE. Sample Page. The Programmatic ID is also known as a Prog ID and results from the combination of Project Name. CI ass Name in the ActiveX control project that implements the property page. The syntax for using the AcW method of the Property Pages collection object is as follows:

Private Sub Appli cation_Opti on s Pag esAdd(ByVal Pages As Property Pages)

Pages.Add "ProgID", Caption End Sub

Figure 9.7 - The Sample Page property page is added to the Tools Options dialog box

Although alternative syntaxes are proposed for the Property Pages Add method in the Microsoft Outlook Visual Basic Reference, the use of the Programmatic ID and the Caption will provide the most trouble-free coding practice. Be aware that if you use the Prog ID argument with the Add method, the Caption argument is mandatory rather than optional. If you omit the Caption argument, Outlook will raise an internal error. Here is a one-line example of using the Opt ions Pag esAdd event to add a property page with a caption of Sample Page to the property pages in the Outlook Tools Options dialog box. The ActiveX control that implements the property page has been compiled so that its ProgID is PPE.SamplePage. The actual code that makes this property page behave as expected is part of the SamplePage ActiveX

Private Sub Application_OptionsPagesAdd(ByVal Pages As Property Pages)

Pages.Add "PPE.SamplePage", "Sample Page" End Sub

The Application Quit event takes place when you exit Outlook. This event provides a location for you to clean up any objects that you have created in the Startup event. It is good programming practice to set any global object variables you have created to Nothing in the Quit event. The following code example illustrates this technique.

Private Sub Application_Quit() On Error Resume Next Set objNS = Nothing Set colExpl = Nothing Set collnsp = Nothing Set objExpl = Nothing Set objlnsp = Nothing End Sub

Reminder

The Reminder event occurs immediately before the reminder for an item is displayed. Outlook passes a generic Item object to the Reminder event procedure. If you want to determine the type of item for which the reminder is going to be displayed, examine the Item's Class property to determine the specific Outlook item type.

Private Sub Application_Reminder(ByVal Item As Object) Select Case Item.Class Case olMail

Msg Box "You are about to receive a message reminder.", _

vb Information Case olAppointment

Msg Box "You are about to receive an appointment reminder.", _

vb Information Case olTask

Msg Box "You are about to receive a task reminder.", vb Information End Select

NEW TO OUTLOOK 2002 The Reminders collection object offers more granular control over Reminder events than the Reminder event on the Application object. If you instantiate a Reminders collection object, you can trigger ReminderAdd, ReminderChange, ReminderFire, ReminderRemove, and Snooze events.

Startup

The Startup event fires when Outlook starts and after any Exchange or COM Add-ins have been loaded. Consequently, you can use the COMAddlns collection object to determine which COM Add-ins have been loaded on startup for the Outlook Application object. The Startup event is also the place where you'll want to create instances of other global object variables that you've declared using the With Events keyword. Object variables that are leading candidates for instantiation in the Startup event are the Inspectors collection object, the Explorers collection object, and the Items collection object for any folders where you want to write event procedure code when an item is added, changed, or removed in a specified folder.

The following example adds a command button to the Standard toolbar of the Outlook Explorer. Outlook 97 and Outlook 98 required C++ coding to achieve the same result. This toolbar button opens the While You Were Out template located in the file system.

Private Sub Application_Startup() Dim objCB As Office. Command Bar Dim objCBB As Office. Command Bar Button

Set objCB = Ap pi i cati on .Active Explorer. Com man dBars("Stan da rd") Set objCBB = objCB.Controls.Add(msoControlButton) With objCBB

.TooltipText = "Open While You Were Out Form" .Style = msoButton Icon .Faceld = 1757

.OnAction = "cmdWhile_Click" End With End Sub

'This OnAction procedure must reside in module-level code 'rather than in ThisOutlookSession Sub cmdWhile_Click() Dim obj Msg As Outlook. Mail Item Dim objlnsp As Outlook.Inspector Set obj Msg = Ap pi i cat ion. Create ItemFromTem pi ate _

("C:\ My Documents\while you were out.oft") Set objlnsp = obj Msg. Get Inspect or obj Msg. Display

'You must display the message before you set WindowState objlnsp.WindowState = ol NormalWindow End Sub

New Application Events in Outlook 2002

The following events are new to Outlook 2002. The AdvancedSe arch Complete and Advance dSearch Stopped events are critical to the functioning of programmatic search using the Advanced Search method of the Application object.

AdvancedSearchComplete

The AdvancedSearchComplete event occurs when the AdvancedSearch method has completed. Use this event to determine when a programmatic search has finished or to start a new procedure upon the completion of the search. The following example displays the Subject for each Results item in the Immediate window when the search is complete:

Private Sub obj Outlook_Adva need Search Complete _ (ByVal SearchObject As Search) Dim col Results As Results Set col Results = Search Object. Results For Each obj Item In col Results Debug. Print obj Item. Subject Next End Sub

AdvancedSearchStopped

The AdvancedSearchStopped event occurs when the Stop method is called on a Search object. If you call the Stop method on a Search object, the Results collection object might not contain complete results for the search.

Both the AdvancedSearchComplete event and the AdvancedSearchStopped event will fire only if the AdvancedSearch method is called programmatically. These events do not occur for a search that executes when a user invokes the Advanced Find dialog box in the Outlook user interface.

MapiLogonComplete

The MapiLogonComplete event occurs after the Application Startup event. When MapiLogonComplete occurs, it means that a valid MAPI session object has been created and that you have full access to all the objects, events, and properties in the Outlook Object Model.

Was this article helpful?

0 0

Post a comment