Chapter 26. Understanding the Outlook Object Model and Key Objects

In this chapter, you'll begin to come to grips with the Outlook object model and using VBA to manipulate Outlook. You'll learn where Outlook stores VBA items, and meet the VBA objects for Outlook's creatable objects and main user interface items, and work with some of the main Outlook objects. You'll explore a variety of objects, from the Application object that represents the entire application through the objects that represent individual messages, calendar items, and tasks. You'll also learn how to search programmatically.

In this chapter you will learn to do the following:

  • Work with the Application object

  • Work with messages

  • Work with calendar items

  • Work with tasks and task requests

  • Search for items

Getting an Overview of the Outlook Object Model

Many people find Outlook harder to work with programmatically than other Office applications, so it's particularly helpful to look over the Outlook object model to see which objects Outlook uses and how they're related. Above all, when working with objects, seeing VBA code examples in the Help system or online can be invaluable.

You can find the Outlook object model reference by following these steps:

  1. Press F1 to open the VBA Editor's Help dialog box.

  2. Then, if the table of contents pane is not visible, click the book icon (second from the right in the row of icons in the Outlook Help dialog box). This opens the table of contents pane.

  3. In the table of contents pane, click Outlook Object Model Reference and you'll see the whole collection of syntax specifications, useful descriptions, and code examples, as shown in Figure 26.1.

The entries in the Outlook Object Model Reference will help you write your own VBA code.

Figure 26.1. The entries in the Outlook Object Model Reference will help you write your own VBA code.

Understanding Where Outlook Stores VBA Items

As you've seen earlier in this book, Word and Excel let you store VBA projects either in a global location (the Normal.dotm template in Word or the Personal Macro Workbook in Excel) or in individual templates or document files. PowerPoint lets you store VBA projects in presentation files and templates.

Outlook, by contrast, doesn't let you store VBA projects in individual items (such as Outlook's email messages or contacts). Instead, Outlook uses a single VBA project called VbaProject.OTM, which is stored in the following folder (instead of Richard in this path, substitute your username):

C:UsersRichardAppDataRoamingMicrosoftOutlook

Understanding Outlook's Creatable Objects and Main User Interface Items

The Application object represents the entire Outlook application, so you can access any Outlook object by going through the Application object. However, Outlook also exposes various creatable objects, allowing you to reach some of the objects in its object model without explicitly going through the Application object. "Creatable" merely means that when you're writing code involving these objects, using the word Application is optional. You can write the following:

Application.Explorers

Or more simply:

Explorers

These are the main creatable objects; you'll meet most of them in more detail later in this chapter and in the next chapter:

  • The Explorers collection contains an Explorer object for each window that displays the contents of a folder.

  • The Inspectors collection contains an Inspector object for each window that's open displaying an Outlook item.

  • The COMAddIns collection contains a COMAddIn object for each COM (Component Object Model) add-in loaded in Outlook.

  • The Reminders collection contains a Reminder object for each reminder.

The most prominent objects in the Outlook user interface are represented in VBA by items whose names are descriptive of their purpose, such as these, for example:

  • The MailItem object represents a mail item.

  • The ContactItem object represents a contact.

  • The TaskItem object represents a task.

  • The AppointmentItem object represents an appointment.

  • The JournalItem object represents a journal entry.

  • The NoteItem object represents a note.

You'll learn how to work with these objects later in this chapter and in the next chapter.

Working with the Application Object

You can have only one instance of Outlook running at a time. (By contrast, you can run multiple instances of Word or Excel at the same time.) You probably won't find this a limitation when you're working within Outlook, but if you create a procedure in another application (such as Word) that will communicate with and manipulate Outlook, you will need to check whether there is an instance of Outlook currently running in the computer before you create an instance programmatically. (See Chapter 30, "Accessing One Application from Another Application," for instructions on accessing one application programmatically from another application.)

Working with the NameSpace Object

To perform many actions with Outlook items such as email messages, tasks, or contacts programmatically, you use the GetNameSpace method of the Application object to return the NameSpace object that represents the root object of the data source. The syntax is as follows:

expression.GetNameSpace(Type)

Here, expression is a required expression that returns an Application object. Type is a required String argument that specifies the type of namespace you want to return. Outlook supports only the MAPI data source, so you always use Type: = "MAPI" with the GetNameSpace method. For example, the following statement returns the NameSpace and uses the CurrentUser property to display the name—the email address—of the current user in a message box:

MsgBox Application.GetNamespace("MAPI").CurrentUser

Accessing Default Folders within the NameSpace Object

The NameSpace object contains the folders that Outlook uses—both the default folders used to store items such as email messages, tasks, and contacts and other folders created by the user or by custom procedures. These folders are represented in Outlook's VBA by MAPIFolder objects that are organized into a Folders collection.

To access the default folders within the NameSpace object, you use the GetDefaultFolder method of the NameSpace object. The syntax is as follows:

expression.GetDefaultFolder(FolderType)

Here, expression is a required expression that returns a NameSpace object. FolderType is a required argument that specifies which default folder you want to return. The constants are self-explanatory: olFolderCalendar, olFolderConflicts, olFolderContacts, olFolderDeletedItems, olFolderDrafts, olFolderInbox, olFolderJournal, olFolderJunk, olFolderLocalFailures, olFolderManagedEmail, olFolderNotes, olFolderOutbox, olFolderRSSFeeds, olFolderSentMail, olFolderServerFailures, olFolderSuggestedContacts, olFolderSyncIssues, olFolderTasks, olFolderToDo, or olPublicFoldersAllPublicFolders.

The following example creates the object variable myCal and assigns the default calendar folder to it:

Dim myCal As MAPIFolder
Set myCal = Application.GetNamespace("MAPI") _
    .GetDefaultFolder(FolderType:=olFolderCalendar)

Accessing Other Folders within the NameSpace Object

Accessing the default folders in the NameSpace object via the GetDefaultFolder method is easy, but often you'll need to access other folders. To do so, use the Folders collection to access a folder.

The following example displays a message box (see Figure 26.2) containing a list of all the folders contained in the namespace:

Sub List_All_NameSpace_Folders()
    Dim myNS As NameSpace
    Dim myFolder As MAPIFolder
    Dim mySubfolder As MAPIFolder
    Dim strFolderList As String

    strFolderList = "Your Outlook NameSpace contains these folders:" _
        & vbCr & vbCr

    Set myNS = Application.GetNamespace("MAPI")
    With myNS
        For Each myFolder In myNS.Folders
            strFolderList = strFolderList & myFolder.Name & vbCr
            For Each mySubfolder In myFolder.Folders
                strFolderList = strFolderList & "*  " & mySubfolder.Name & vbCr
Next mySubfolder
        Next myFolder

    End With
    MsgBox strFolderList, vbOKOnly + vbInformation, "Folders in NameSpace"

End Sub
Listing the folders contained in the NameSpace object

Figure 26.2. Listing the folders contained in the NameSpace object

Creating a New Folder

To create a new folder, use the Add method with the Folders collection. The syntax is as follows:

expression.Add(Name, Type)

Here, expression is a required expression that returns a Folders collection. Name is a required String argument that specifies the display name to assign to the new folder. Type is an optional Long argument that you can use to specify the type of folder to create: olFolderCalendar, olFolderContacts, olFolderDrafts, olFolderInbox, olFolderJournal, olFolder Notes, or olFolderTasks. If you omit Type, Outlook assigns the new folder the same type as its parent folder (the folder in which you create the new folder).

The following statement creates a new folder named Personal Tasks in the Tasks folder, assigning the new folder the olFolderTasks folder type explicitly for clarity:

Application.GetNamespace("MAPI").GetDefaultFolder(olFolderTasks) _
    .Folders.Add Name:="Personal Tasks", Type:=olFolderTasks

Deleting a Folder

To delete a folder, use the Delete method with the appropriate MAPIFolder object. This method takes no arguments. The following example deletes the folder named Personal Tasks in the Tasks folder:

Application.GetNamespace("MAPI").GetDefaultFolder(olFolderTasks) _
    .Folders("Personal Tasks").Delete

Working with Inspectors and Explorers

VBA uses two major Outlook objects that most users wouldn't recognize from working with the Outlook user interface alone:

  • An Inspector is an object that represents a window displaying an Outlook item, such as an email message or an appointment.

  • An Explorer object represents a window that displays the contents of a folder.

Opening an Inspector Window

To open an inspector window for an object, use the Display method of the Inspector object. For example, the following statement displays an inspector window for the object referenced by the object variable myItem:

myItem.Display

Returning the Inspector Associated with an Item

To return the inspector associated with an item, use the GetInspector property of the appropriate object. The following example returns the inspector for the item identified by the object variable myItem:

myItem.GetInspector

Returning the Active Window, Inspector, or Explorer

Unlike Word, Excel, and PowerPoint, Outlook doesn't have an ActiveWindow object that represents the active window. However, Outlook's Application object does have an ActiveWindow method, which returns the topmost Outlook window. (If there is no window, ActiveWindow returns Nothing.)

This window will be either an Inspector object or an Explorer object. Similarly, the ActiveExplorer method of the Application object returns the active explorer, and the ActiveInspector method of the Application object returns the active inspector.

You can use the TypeName function to determine which type of window is active. The following example displays a message box that states which window type is active if there is an active window:

If Not TypeName(ActiveWindow) = "Nothing" Then
    MsgBox "An " & TypeName(ActiveWindow) & " window is active."
End If

Working with the Active Inspector

In many procedures, you'll need to determine what the topmost inspector in the Outlook application is, either so that you can work with that inspector or so that you can restore the inspector to the topmost position at the end of a procedure that manipulates other inspectors. (Remember, you should always try to restore an application to the state it was in when your procedure started execution. This is a courtesy to the user and evidence of careful, quality programming.)

To find out which is the topmost inspector, use the ActiveInspector method of the Application object. For example, the following statement maximizes the window of the topmost inspector:

Application.ActiveInspector.WindowState = olMaximized

But because there isn't always an active inspector in Outlook, it's a good idea to make sure there is an active inspector before you try to manipulate it. To do so, check that the TypeName function does not return Nothing when run on the ActiveInspector method of the Application object:

If TypeName(Application.ActiveInspector) = "Nothing" Then
    MsgBox "No item is open."
    End
End If

Creating Items

To create new items in Outlook, you use the CreateItem method or the CreateItemFromTemplate method of the Application object. The CreateItem method creates default items, while the CreateItemFromTemplate method creates items based on the templates you specify.

Using the CreateItem Method to Create Default Items

The syntax for the CreateItem method is as follows:

expression.CreateItem(ItemType)

Here, expression is a required expression that returns an Application object. ItemType is a required argument that specifies the type of item to create: olContactItem, olDistributionListItem, olJournalItem, olMailItem, MobileItemMMS, MobileItemSMS, olNoteItem, olPostItem, or olTaskItem.

The following example creates a new email message; assigns a recipient (by setting the To property), a subject (by setting the Subject property), and body text (by setting the Body property); and then displays the message window:

Dim myMessage As MailItem
Set myMessage = Application.CreateItem(ItemType:=olMailItem)
With myMessage
    .To = "[email protected]"
    .Subject = "Test message"
    .Body = "This is a test message."
    .Display
End With

Using the CreateItemFromTemplate Method to Create Items Based on Templates

Instead of creating a default item by using the CreateItem method, you can use the CreateItemFromTemplate method of the Application object to create a new item based on a template. The syntax for the CreateItemFromTemplate method is as follows:

expression.CreateItemFromTemplate(TemplatePath, InFolder)

Here, expression is a required expression that returns an Application object. TemplatePath is a required String argument that specifies the path and filename of the template on which to base the new item. InFolder is an optional Variant argument that you can use to specify the folder in which to create the item. If you omit the InFolder argument, Outlook creates the item in the default folder for that item type.

The following example creates a new note item based on the custom template tpltNote.oft stored in the C:UsersYOURNAMEAppDataRoamingMicrosoftTemplates folder within the user's user profile (substitute your computer's name for YOURNAME). The example then displays the new note item:

Dim myNoteItem As NoteItem

Set myNoteItem = Application.CreateItemFromTemplate _
("C:UsersRichardAppDataRoaming" _
& "MicrosoftTemplates	pltNote.oft")
myNoteItem.Display

This note template was created by pressing Ctrl+Shift+N in Outlook to create a new note, then choosing File

Using the CreateItemFromTemplate Method to Create Items Based on Templates

Quitting Outlook

To quit Outlook, use the Quit method of the Application object. This method takes no arguments:

Application.Quit

You may also want to work with the events available to the Application object. See Chapter 27, "Working with Events in Outlook," for a discussion of how to work with these application-level events and with item-level events.

Understanding General Methods for Working with Outlook Objects

Many of the objects in Outlook use the methods covered in the following sections. You'll see brief examples showing you how to use the methods as well as further examples on the individual types of objects—email messages, appointments, contacts, tasks, and so on—later in this chapter and in the next.

Using the Display Method

To open an item in an inspector window, use the Display method. The syntax is as follows:

expression.Display(Modal)

Here, expression is a required expression that returns the type of object you want to display—for example, a ContactItem object or a MailItem object. Modal is an optional Variant argument that you can set to True to make the window modal instead of having it be modeless as it is by default or if you set Modal to False. Making the window modal means that users must close the window before they can work with another window.

Note that the Modal argument isn't available for Explorer and MAPIFolder objects.

For example, the following statement uses the Display method to display the Inbox:

Application.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox).Display

Using the Close Method

To close a window, use the Close method. The syntax is as follows:

expression.Close(SaveMode)

Here, expression is a required expression that returns the object you want to close. SaveMode is a required argument that specifies whether to save changes (olSave), discard the changes (olDiscard), or prompt the user to decide whether to save the changes (olPromptForSave).

The following example closes the active inspector and saves changes to its contents:

ActiveInspector.Close SaveMode:=olSave

Using the Delete Method

To delete an item, use the Delete method. This method takes no arguments. The following example deletes the item with the index number 1 in the Contacts folder:

Application.GetNamespace("MAPI").GetDefaultFolder(olFolderContacts) _
    .Items(1).Delete

Using the PrintOut Method

To print an item, use the PrintOut method. This method takes no arguments. The following example prints the item with the index number 1 in the Inbox:

Application.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox) _
    .Items(1).PrintOut

Using the Save Method

To save an item, use the Save method. This method takes no arguments. The following example creates a new task; assigns it a subject, start date (today), and due date (a week from today); turns off the reminder for the task; and then saves it:

Dim myTask As TaskItem
Set myTask = Application.CreateItem(ItemType:=olTaskItem)
With myTask
    .Subject = "Arrange Review Meeting"
    .StartDate = Date
    .DueDate = Date + 7
    .ReminderSet = False
    .Save
End With

Using the SaveAs Method

To save an item as a separate file, use the SaveAs method. The syntax is as follows:

expression.SaveAs(Path, Type)

Here, expression is a required expression that returns the object to be saved. Path is a required String argument that specifies the path and filename under which to save the file. Type is an optional Variant argument that you can use to control the file type used for the file, as shown in Table 26.1.

Table 26.1. Type arguments for the SaveAs method

Argument

Type of File

olHTML

HTML file

olMHTML

MHTML file (MIME HTML)

olMSG

Outlook message format (.msg filename extension)

olRTF

Rich Text format

olTemplate

Template

olDoc

Word document format (email messages using WordMail)

olTXT

Text file

olVCal

vCal file

olVCard

vCard file

olICal

iCal file

olMSGUnicode

Outlook Unicode message format (.msg filename extension)

The following example saves the message open in the active inspector. If the IsWordMail property of the ActiveInspector object returns True, the example saves the message as a .doc file; if the IsWordMail property returns False, the example saves the message as an .rtf file. If no inspector window is active, the example displays a message box pointing out the problem to the user:

If TypeName(ActiveInspector) = "Nothing" Then
    MsgBox "This macro cannot run because " & _
        "there is no active window.", vbOKOnly, "Macro Cannot Run"
    End
Else
    If ActiveInspector.IsWordMail Then
        ActiveInspector.CurrentItem.SaveAs "c:keepmessage.doc"
    Else
        ActiveInspector.CurrentItem.SaveAs "c:keepmessage.rtf"
    End If
End If

Working with Messages

If you or your colleagues use Outlook's email capabilities extensively, you may be able to save time by programming Outlook to create or process messages automatically. The following sections show you how to create a new message, work with its contents, add an attachment, and send the message.

Creating a New Message

To create a new message, use the CreateItem method of the Application object and specify olMailItem for the ItemType argument. The following example creates a MailItem object variable named myMessage and assigns to it a new message:

Dim myMessage As MailItem
Set myMessage = Application.CreateItem(ItemType:=olMailItem)

Working with the Contents of a Message

To work with the contents of a message, set or get the appropriate properties. These are the most widely useful properties:

  • To is the recipient or recipients of the message.

  • CC is the recipient or recipients of copies of the message.

  • BCC is the recipient or recipients of blind copies of the message.

  • Subject is the subject line of the message.

  • Body is the body text of the message.

  • BodyFormat is the message's formatting type: olFormatPlain for text only, olFormatRichText for text with formatting, and olFormatHTML for HTML formatting.

  • Importance is the relative importance of the message. Set it to olImportanceHigh, olImportanceNormal, or olImportanceLow.

The following example creates a new message item and assigns it to the object variable myMessage. It then adds an addressee, a subject, and body text; applies the HTML format; sets the importance to high; and sends the message:

Dim myMessage As MailItem
Set myMessage = Application.CreateItem(ItemType:=olMailItem)
With myMessage
    .To = "[email protected]"
    .Subject = "Preparation for Review"
    .Body = "Please drop by tomorrow and spend a few minutes" _
        & " discussing the materials we need for Darla's review."
    .BodyFormat = olFormatHTML
    .Importance = olImportanceHigh
    .Send
End With

Adding an Attachment to a Message

To add an attachment to a message, use the Add method with the Attachments collection, which you return by using the Attachments property of the MailItem object. The syntax is as follows:

expression.Add(Source, Type, Position, DisplayName)

Here are the components of the syntax:

  • expression is a required expression that returns an Attachments collection.

  • Source is a required String argument that specifies the path and filename of the attachment.

  • Type is an optional String argument that you can use to specify the type of attachment.

  • Position is an optional String argument that you can use with rich-text messages to specify the character at which the attachment is positioned in the text. Use character 0 to hide the attachment, 1 to position the attachment at the beginning of the message, or a higher value to position the attachment at the specified character position. To position the attachment at the end of the message, use a number higher than the number of characters in the message.

  • DisplayName is an optional String argument that you can specify to control the name displayed for the attachment in the message.

The following example attaches to the message referenced by the object variable myMessage the file Corporate Downsizing.pptm stored in the folder Y:Sample Documents, positioning the attachment at the beginning of the message and setting its display name to Downsizing Presentation:

myMessage.Attachments.Add _
    Source:="Y:Sample DocumentsCorporate Downsizing.pptm", _
    Position:=1, DisplayName:="Downsizing Presentation"

Sending a Message

To send a message, use the Send method. This method takes no arguments. The following example sends the message referenced by the object variable myMessage:

myMessage.Send

To check whether a message has been sent, check its Sent property. This Boolean property returns True if the message has been sent and False if it has not.

Working with Calendar Items

If you create or receive many calendar items, you may be able to save time or streamline your scheduling by using VBA. The following sections show you how to create a calendar item and work with its contents.

Creating a New Calendar Item

To create a new calendar item, use the CreateItem method of the Application object and specify olAppointmentItem for the ItemType argument. The following example creates an AppointmentItem object variable named myAppointment and assigns to it a new appointment item:

Dim myAppointment As AppointmentItem
Set myAppointment = Application.CreateItem(ItemType:=olAppointmentItem)

Working with the Contents of a Calendar Item

To work with the contents of a calendar item, set or get the appropriate properties. These are the most widely useful properties:

  • Subject is the subject of the appointment.

  • Body is the body text of the appointment.

  • Start is the start time of the appointment.

  • End is the end time of the appointment.

  • BusyStatus is your status during the appointment: olBusy, olFree, olOutOfOffice, or olTentative.

  • Categories is the category or categories assigned to the item.

  • ReminderSet determines whether the appointment has a reminder (True) or not (False).

  • ReminderMinutesBeforeStart is the number of minutes before the event that the reminder should occur.

The following example creates a new AppointmentItem object and assigns it to the object variable myAppointment. It then sets the subject, body, start date (2:30 p.m. on the day seven days after the present date), and end date (one hour after the start); marks the time as busy; assigns the Personal category; sets a reminder 30 minutes before the appointment; and saves the appointment:

Dim myAppointment As AppointmentItem
Set myAppointment = Application.CreateItem(ItemType:=olAppointmentItem)
With myAppointment
    .Subject = "Dentist"
    .Body = "Dr. Schmitt " & vbCr & "4436 Acacia Blvd."
    .Start = Str(Date + 7) & " 2.30 PM"
    .End = Str(Date + 7) & " 3.30 PM"
    .BusyStatus = olBusy
    .Categories = "Personal"
    .ReminderMinutesBeforeStart = 30
    .ReminderSet = True
    .Save
End With

Working with Tasks and Task Requests

VBA can automate tasks and task requests. The following sections show you how to create a task, work with the contents of a task item, and send a task request.

Creating a Task

To create a new task item, use the CreateItem method of the Application object and specify olTaskItem for the ItemType argument. The following example creates a TaskItem object variable named myTask and assigns to it a new task item:

Dim myTask As TaskItem
Set myTask = Application.CreateItem(ItemType:=olTaskItem)

Working with the Contents of a Task Item

To work with the contents of a task item, set or get the appropriate properties. These are the most widely useful properties:

  • Subject is the subject of the task.

  • Body is the body text of the task.

  • Start is the start time of the task.

  • DueDate is the due date of the task.

  • Importance is the importance of the task. Set it to olImportanceHigh, olImportanceNormal, or olImportanceLow.

  • Status is the status of the task: olTaskNotStarted, olTaskWaiting, olTaskDeferred, olTaskInProgress, or olTaskComplete.

  • PercentComplete is the percentage of the task completed.

  • Companies is the companies associated with the task.

  • BillingInformation is the company or department to bill for the task.

The following example creates a TaskItem object variable named myTask and assigns to it a new task item. It then sets the subject and body of the task, specifies a due date, sets the status to olTaskInProgress and the percentage complete to 10, specifies the company involved and who to bill, sets the importance to High, and then saves the task:

Dim myTask As TaskItem
Set myTask = Application.CreateItem(ItemType:=olTaskItem)
With myTask
    .Subject = "Create a business plan"
    .Body = "The business plan must cover the next four years." & _
        vbCr & vbCr & "It must provide a detailed budget, " & _
        "staffing projections, and a cost/benefit analysis."
    .DueDate = Str(Date + 28)
    .Status = olTaskInProgress
    .PercentComplete = 10
.Companies = "Acme Polyglot Industrialists"
    .BillingInformation = "Sales & Marketing"
    .Importance = olImportanceHigh
    .Save
End With

Assigning a Task to a Colleague

To assign a task to a colleague, use the Assign method of the TaskItem object, and then use the Add method of the Recipients collection to add one or more recipients. Finally, you can use the Send method to send the task to your colleague.

The following example creates a task, uses the Assign method to indicate that it will be assigned, specifies a recipient, and sends the task:

Dim myTaskAssignment As TaskItem
Set myTaskAssignment = Application.CreateItem(ItemType:=olTaskItem)
With myTaskAssignment
    .Assign
    .Recipients.Add Name:="Peter Nagelly"
    .Subject = "Buy Bagels for Dress-Down/Eat-Up Day"
    .Body = "It's your turn to get the bagels on Friday."
    .Body = .Body & vbCr & vbCr & "Remember: No donuts AT ALL."
    .DueDate = Str(Date + 3)
    .Send
End With

Searching for Items

To search for items, use the AdvancedSearch method of the Application object. The syntax is as follows:

expression.AdvancedSearch(Scope, Filter, SearchSubFolders, Tag)

Here are the components of the syntax:

  • expression is a required expression that returns an Application object.

  • Scope is a required String argument that specifies the scope of the search (which items to search). Usually you'll search a particular folder. For example, you might search the Inbox for messages that match certain criteria, or you might search the Tasks folder for particular tasks.

  • Filter is an optional Variant argument that specifies the search filter. While this argument is optional, you will need to use it unless you want to return all the items within the scope you've specified.

  • SearchSubFolders is an optional Variant argument that you can set to True to search through any subfolders of the folder specified by the Scope argument or False to search only the specified folder. The default is False.

  • Tag is an optional Variant argument that you can use to specify a name for the search you're defining. If you create a name, you can call the search again.

The complex part of performing an advanced search is creating the search filter, which needs to be in DASL format. But you can have Outlook put together the filter for you. To do so, first put the Filter button on the Quick Access Toolbar (above the Ribbon) by following these steps:

  1. In Outlook, click the small down-arrow symbol in the Quick Access Toolbar (in the upper-left corner of the Outlook window).

  2. Click the More Commands option in the drop-down list.

  3. In the Outlook Options dialog box, open the list under Choose Commands From.

  4. In the drop-down list, select the All Commands option.

  5. Scroll down until you locate the Filter option, then double-click to add it to the list of displayed toolbar items (in the Customize The Quick Access Toolbar list on the right).

  6. Click OK to close the dialog box.

Now you can display the Filter dialog box and put the filter together:

  1. Click the Filter button on the toolbar to display the Filter dialog box (see Figure 26.3).

  2. Use the controls on the Tasks, More Choices, and Advanced pages to specify the filter you want.

  3. Click the SQL tab to display the SQL page, which now contains the filter that you've created.

  4. Select the "Edit These Criteria Directly. All Other Tabs Will Be Unavailable" check box to make the filter text (in the Find Items That Match These Criteria text box) available for copying.

  5. Drag with the mouse to select the filter, and then press Ctrl+C to copy it to the Clipboard.

  6. Click the Cancel button to close the Filter dialog box.

  7. Press Alt + F11 to switch to the Visual Basic Editor, and then paste the filter into your code.

The following example searches the Inbox (Scope: = "Inbox" ) for messages with the subject line Dam Project (Filter: = "urn:schemas:mailheader:subject = 'Dam Project'"). If any messages are found, the procedure produces a list of sender names, which it assigns to the String variable strMessages. If no messages are found, the procedure assigns to strMessages text to let the user know this. The procedure then displays strMessages in a message box with the caption Search Results:

Sub Sample_Advanced_Search()

    Dim mySearch As Search
Dim myResults As Results
    Dim intCounter As Integer
    Dim strMessages As String

    Set mySearch = AdvancedSearch(Scope:="Inbox", _
        Filter:="urn:schemas:mailheader:subject = 'Dam Project'')
    Set myResults = mySearch.Results
    If myResults.Count > 0 Then
        strMessages = "The Inbox contains messages that match " & _
            "the search criteria from these senders:" & vbCr & vbCr
    For intCounter = 1 To myResults.Count
        strMessages = strMessages & _
            myResults.Item(intCounter).SenderName & vbCr
    Next intCounter
    Else
        strMessages = "The Inbox contains no messages " & _
            "that match the search criteria."
    End If
    MsgBox strMessages, vbOKOnly, "Search Results"
End Sub
Use the Tasks, More Choices, and Advanced pages of the Filter dialog box to have VBA generate the DASL filter needed for an advanced search.

Figure 26.3. Use the Tasks, More Choices, and Advanced pages of the Filter dialog box to have VBA generate the DASL filter needed for an advanced search.

The Bottom Line

Work with the Application object

VBA uses two major Outlook objects that most users wouldn't recognize from working with the Outlook user interface alone.

Master It

One of these objects represents a window that displays the contents of a folder. The other represents a window displaying an Outlook item, such as an email message or an appointment. What are the names of these two objects?

Work with messages

To work with the contents of a message in VBA, you set or get various properties.

Master It

Name one of the most widely useful properties employed when manipulating the contents of a message in a procedure.

Work with calendar items

You can create new calendar appointment items via VBA.

Master It

To create a new calendar item, you use a particular method of the Application object and specify olAppointmentItem for the ItemType argument. What is the method?

Work with tasks and task requests

You can assign a task to a colleague and then add one or more recipients. You can then send the task to your colleague and, optionally, the additional recipients.

Master It

What methods do you use to assign, add, and send a task to others?

Search for items

The hard part—and it's a very hard part—of using the Filter argument to search for items with the AdvancedSearch method is building the filter text itself. Creating the proper syntax for this argument is quite complicated. There is, however, a good shortcut that vastly simplifies generating the proper syntax.

Master It

What is the efficient, quick way to create the proper syntax for the Filter argument?

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.187.113