Code Examples

In this section, we’ll take a look at some examples that more fully illustrate some of the things you can do using VBA in Outlook.

Example 18-1 is a macro that opens all high-priority mail items in your Inbox. Notice that the macro is declared as a public subprocedure with an empty parameter list.

Example 18-1. Opening High Priority Mail Items in Your Inbox

Public Sub OpenHighPriorityMsgs(  )
    ' Declare some object variables.
    Dim mapiNamespace As NameSpace
    Dim inboxItems As Items
    Dim hiPriorityMsgs As Items
    
    ' Get the MAPI namespace.
    Set mapiNamespace = Application.GetNamespace("MAPI")
    
    ' Get all the items in the Inbox.
    Set inboxItems = _
          mapiNamespace.GetDefaultFolder(olFolderInbox).Items
    
    ' Get the subset of Inbox items with high importance.
    Set hiPriorityMsgs = _
          inboxItems.Restrict("[Importance] = 'High'")
    
    ' Display each high-priority mail message.
    For Each msg In hiPriorityMsgs
        msg.display
    Next
    
    ' Clean up our object variables.
    Set hiPriorityItems = Nothing
    Set inboxItems = Nothing
    Set mapiNamespace = Nothing
End Sub

After we get the MAPI namespace, we grab all of the items in the Inbox into an Items collection (inboxItems). We then get a subset of these items (another Items collection) through the Items collection’s Restrict method, which filters the collection based on given criteria. Here, we’re indicating that we only want items with high importance. We use the For...Each construct to display (open in an Inspector for) each item in the filtered collection. On the ...

Get Outlook 2000 in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.