Using Visual Basic, VBA, or VBScript! with Outlook

출처: http://msdn.microsoft.com/en-us/library/aa155615.aspx

 

Microsoft Outlook 2002 Book Excerpts
Building Applications with Microsoft Outlook Version 2002

Chapter 11: Using Visual Basic, VBA, or VBScript! with Outlook

Randy Byrne
Micro Eye, Inc.

December 2002

Applies to:
Microsoft? Outlook? 2002
Microsoft Visual Basic? Buy this book

Summary: This article presents an excerpt from the book Building Applications with Microsoft Outlook Version 2002 by Randy Byrne. (115 printed pages)

Contents

The Application Object
The NameSpace Object
The Outlook Window (Explorer Objects)
The Panes Collection Object
The OutlookBarPane Object
The OutlookBarStorage Object
The OutlookBarGroups Collection Object
The OutlookBarGroup Object
The OutlookBarShortcuts Collection Object
The OutlookBarShortcut Object
The CommandBars Collection Object
Overview of Command Bars
The CommandBar Object
The CommandBarControls Collection Object
The CommandBarControl Object
The CommandBarButton Object
The CommandBarComboBox Object
The CommandBarPopup Object
The AddressLists Collection Object
The AddressList Object
The AddressEntries Collection Object
The AddressEntry Object
Using CDO to Obtain Recipients
The Folders Collection Object
The MAPIFolder Object
The Views Collection Object
The Items Collection Object
The PostItem Object
The MailItem Object
The DocumentItem Object
The AppointmentItem Object
The MeetingItem Object
The TaskItem Object
The TaskRequestItem Object
The ContactItem and DistListItem Objects
The JournalItem Object
The Item Window (Inspector Objects)
The Pages Collection Object
The Page Object
The Controls Collection Object
The Control Object
The UserProperties Collection Object
The ItemProperties Collection Object
The Recipients Collection Object
Automation
Where To Go from Here

This chapter primarily addresses the use of Microsoft? Visual Basic? Scripting Edition (VBScript!) in Microsoft Outlook? forms. It looks at the objects of the Outlook Object Model and provides programming examples in VBScript! or Visual Basic. Most of the code examples in VBScript! can be extended directly in Outlook Visual Basic for Applications (VBA) or Visual Basic. Exceptions are noted accordingly. You should carefully consider the impact of the Outlook E-Mail Security Update on forms and application-level code. For additional information on the programmatic implications of the object model guard in Outlook 2002, see Chapter 13, “Distributing and Securing Applications.”

This chapter is designed to give you the fundamental skills and knowledge you need to create collaborative applications using Visual Basic and VBScript!. You’ll find items demonstrating almost all the code examples in this chapter in the VBScript! Samples folder. This chapter covers how to

  • Modify command bars.
  • Create a programmatic search.
  • Modify views.
  • Set folders programmatically for offline use.
  • Snooze and dismiss reminders.
  • Reference a folder collection or a folder in the Folder List.
  • Create, open, send, and post standard and custom items.
  • Open and close standard and custom forms.
  • Set and change field values in items.
  • Hide or show a form page.
  • Change the properties of a control on a page.
  • Specify the recipients of an item.

To open the VBScript! Samples folder

In the Folder List, expand the Building Microsoft Outlook 2002 Applications folder, expand folder 4. Beyond the Basics, expand the VBScript! folder, and then click the VBScript! Samples folder.

The Application Object

The Application object sits at the top of the object model and represents the entire Outlook application. The Outlook Application object has several purposes:

  • As the root object, it enables you to reference other objects in the Outlook object hierarchy.
  • It provides methods such as CreateItem and CreateObject so that you can create new items and reference them without moving through the object hierarchy.
  • It provides methods for directly referencing the active Outlook window or form.

More Info   For a complete list and description of the methods, properties, and events for the Application object, see Microsoft Outlook Visual Basic Reference Help. Also see the Visio document entitled “Outlook 2002 Object Model Extended View” in the Outlook 2002 Object Model folder under the Visual Basic for Applications folder under the 4. Beyond the Basics folder. This object model diagram shows the properties, methods, and events for every object in the Outlook object model.

Import!ant   Open the Application object item in the VBScript! Samples folder to work directly with this code in Outlook.

Application Object Methods

This section covers the ActiveExplorer, ActiveWindow, AdvancedSearch, CopyItem, CreateItem, CreateObject and GetNameSpace methods.

Returning the active window

You can use the ActiveWindow method of the Application object to return the topmost active Outlook window. The ActiveWindow method returns either an Explorer or an Inspector object, depending on the actual active window.

The following example sets the MyExplorer object to the currently active Outlook Explorer window, displays a message that indicates the active window type, and then redisplays the item window when the ShowOutlookActiveExplorer control is clicked:

Creating a standard item

You can use the CreateItem method of the Application object to create and return Outlook standard items such as a Message item, a Post item, or an Appointment item. The following example creates a Message item using the default editor and displays it when CreateAMailMessage is clicked:

The next simple example creates an HTML message.

It’s useful to know that you can also create a Word Envelope message in code. The following example uses the CreateObject method to launch Word and display a Word Envelope message. From the standpoint of the message body, Word Envelope messages are equivalent to HTML messages.

The following table lists the numeric values you use as arguments for the CreateItem method. You can also copy the CONST declarations in the Enum OlItemType section of the Outlook Constants item in the VBScript! Samples folder and paste them into your code.

Type of Item Value
Appointment 1
Contact 2
Distribution List 7
Journal 4
Mail Message 0
Note 5
Post 6
Task 3

More Info   For more information about creating custom items, see “Items Collection Methods” later in this chapter.

Creating an Automation object

You can use the CreateObject method of the Application object to create Automation objects, such as Microsoft Excel, Microsoft Access, or Microsoft Word objects. You can also use the CreateObject method to create instances of custom ActiveX DLLs that extend the functionality of Outlook. The following example uses the CreateObject method to create an instance of Excel, adds a workbook, and then renames the first sheet in the workbook to Outlook CreateObject Example:

Tip   When you are writing Automation code for VBScript! in Outlook forms, you can expedite the development process by using the VBA Editor in Outlook to write the code and then pasting the code into VBScript!. As noted in the example above, you must place comment marks before the As keyword in the object type declarations, or VBScript! will raise an error. The beauty of this approach is that you have all the IntelliSense features of the VBA Editor at your disposal, including auto list members, syntax checking, parameter information, quick information, and code formatting. Before you begin, set references to the appropriate object libraries by using the Tool menu’s References command in the VBA Editor window.

Copying an item from the File System

The CopyItem method is new to Outlook 2002. It lets you copy an item from the File System to an Outlook folder. The following code example creates a Word document in the temporary folder, adds some text to the document, and then uses the CopyItem method to copy the document to the user’s Inbox folder. Note that the CopyItem method accepts a string for the path to the destination folder instead of a MAPIFolder object.

Returning a MAPI NameSpace object

You can use the GetNameSpace(“MAPI”) method of the Application object to return the MAPI message store.

In the following example, the GetNameSpace method returns the NameSpace object. The Offline property of the NameSpace object is then used to display a message box indicating whether the user is on line or off line.

Import!ant   The only data source currently supported is MAPI, which allows access to all Outlook data stored in MAPI. For this reason, the GetNameSpace method must always appear in Outlook as GetNameSpace(“MAPI”).

Creating Office objects

The Application object has several child objects that are actually members of the Microsoft Office Object Model. For example, the Application object contains member objects for the Office AnswerWizard, Assistant, COMAddIns, and LanguageSettings objects. The following code example uses an animated Assistant to display the LanguageID settings for the Outlook Application object.

Creating a programmatic search

The ability to create a programmatic search using the AdvancedSearch method of the Application object is new to Outlook 2002. AdvancedSearch returns a Search object, which in turn contains a Results object that you can use to iterate over the items contained in that Results object. A Results object is identical to an Items collection object. You use the AdvancedSearch method in conjunction with the AdvancedSearchComplete event for the Application object. When the AdvancedSearchComplete event fires, you’ll know that the Search object for your query is available for further processing. Assign a Tag value in your call to AdvancedSearch so that you can identify the correct Search object in the

AdvancedSearchComplete event. See Chapter 9, “Raise Events and Move to the Head of the Class,” for additional details on the AdvancedSearchComplete event and Chapter 14, “Creating COM Add-Ins with Visual Basic,” for a discussion of the sample Search add-in.

AdvancedSearch takes four arguments, two of which are enigmatically explained in Outlook Visual Basic Help. Here is the syntax for a call to AdvancedSearch:

Both the Scope and Filter arguments can be understood in the context of Microsoft Exchange 2000 Web Storage queries. Although you don’t have to run against an Exchange 2000 server to use AdvancedSearch, you should consult the Exchange SDK to gain a complete understanding of Web Storage System SQL. The Exchange SDK is available on the Web at http://msdn.microsoft.com/exchange and is also included on this book’s companion CD. See the section entitled “Web Storage System SQL.”

Fortunately, there are quicker and less painful ways to get up to speed with Filter and Scope syntax. You can use an undocumented Registry key to display a Query Builder page on the Filter dialog box associated with the View Summary dialog box. (See Figure 11-1.) After you use the Query Builder to construct your query, you can then copy the Filter syntax displayed on the SQL page and paste it into your code. Do not attempt to add the Query Builder page Registry setting unless you are familiar with the Microsoft Windows? Registry Editor.

Figure 11-1. The undocumented Query Builder page on the Filter dialog box

To display the Query Builder page on the Filter dialog box

  1. Click Start, point to Run, type Regedit in the Run dialog box, and then click OK to launch the Windows Registry editor.
  2. In the Registry tree, navigate to HKEY_CURRENT_USER\Software\Microsoft\Office\10.0\Outlook.
  3. Select New from the Edit menu, and then select Key from the New submenu.
  4. Type QueryBuilder in the Key edit box. Regedit will suggest New Key #1, but you should replace that key name with QueryBuilder.

To build a filter using the Query Builder page on the Filter dialog box

  1. In Outlook, select Current View from the View menu and then select Customize Current View from the Current View submenu.
  2. Click the Filter button on the View Summary dialog box.
  3. Click the Query Builder page on the Filter dialog box.
  4. Use the Query Builder interface to build your query. When you construct a filter, you actually build a WHERE clause without the WHERE keyword. Notice that you can use the logical AND or logical OR operator to develop the query and move clauses up or down.
  5. Click the SQL page shown in Figure 11-2 on the Filter dialog box, and clear the Edit These Criteria Directly check box. Once you clear the check box, you can copy the query by selecting it and pressing Ctrl+C to copy to the Clipboard.
  6. Because you don’t want to modify the view, click Cancel to dismiss the Filter dialog box. Then click Cancel again to dismiss the View Summary dialog box.

Once you have constructed your Filter string, the rest of the process is relatively straightforward. The Scope argument can use either an unqualified folder name such as Inbox, Drafts, Tasks, or a folder path in a Web Storage System SQL Scope clause. SearchSubFolders is Boolean and will work only in a Mailbox or PST store. If you’re searching a public folder, you can search only one folder at a time. This is a built-in limitation of the MAPI Public Folder store. As stated previously, you should use the AdvancedSearchComplete event to process the Search object returned by AdvancedSearch. This next code example shows you how to construct a programmatic search and displays the user form shown in Figure 11-3 when the search is complete.

Figure 11-2. Copy a Filter string from the SQL page of the Filter dialog box to provide the Filter argument for the AdvancedSearch method.

Figure 11-3. Display a custom dialog box that shows the results of a programmatic search in a ListView control.

The NameSpace Object

In Outlook, the NameSpace object represents the MAPI message store. The NameSpace object provides methods for logging on or off Outlook, referencing a default folder, and returning objects directly by ID. In addition, the NameSpace object provides access to a variety of methods and properties that are not normally available with the Application object.

More Info   For a complete list and description of the methods, properties, and events for the NameSpace object, see Microsoft Outlook Visual Basic Reference Help.

Import!ant   Open the NameSpace object item in the VBScript! Samples folder to work directly with this code in Outlook.

NameSpace Object Methods

This section covers the GetDefaultFolder method and the dial method of the NameSpace object.

Returning a default folder

You can use the GetDefaultFolder method of the NameSpace object to access folders in the root folder, also known as the Mailbox. To reference a folder in the Mailbox, you can either specify a numeric value as the argument in the GetDefaultFolder method or copy the olDefaultFolders constants from the Outlook Constants item in the VBScript! Samples folder and paste them into your code. The table on the following page lists these numeric values.

The following example uses the GetDefaultFolder method of the NameSpace object to return the Contacts folder and then display it:

Folder Value
Deleted Items 3
Outbox 4
Sent Items 5
Inbox 6
Calendar 9
Contacts 10
Journal 11
Notes 12
Tasks 13
Drafts 16

Dialing a phone number

The Dial method is new to Outlook 2002. If you supply a ContactItem as the argument to the Dial method, you will display the Outlook automatic phone dialer for that contact. The following code example uses the Dial method for the first ContactItem in your Contacts folder:

Properties of the NameSpace Object

The NameSpace object provides two properties that you use quite often. These are the CurrentUser and Folders properties.

Returning the name of the current user

You can use the CurrentUser property of the NameSpace object to return the name of the currently logged-on user. This example shows the current user’s name in the message box when the CommandButton1 control is clicked:

Referencing a folder collection

You can use the Folders property of the NameSpace object to reference the collection of folders in the MAPI NameSpace. The following example displays the number of subfolders in the Building Microsoft Outlook 2002 Applications .pst file:

Selecting a folder

You can use the PickFolder method of the NameSpace object to return a MAPIFolder object. The PickFolder method displays a dialog box for the user to select a folder from all available folders in the current profile. The following example displays the Select Folders dialog box and also displays an alert! dialog box if the user clicks Cancel. If the user selects a folder, then the folder is displayed in an Explorer window.

The Outlook E-Mail Security Update object model guard

If you’re using Outlook 2002 or a version of Outlook 2000 or Outlook 98 with the Outlook E-Mail Security Update installed, the code shown in CommandButton1_Click will display a Warning dialog box, as shown in Figure 11-4. Accessing the CurrentUser property causes the Warning dialog box to appear. The object model guard component of the Outlook E-Mail Security Update figures prominently in this chapter. Wherever possible, I will suggest workarounds for blocked object model properties and methods. Remember that developers targeting Exchanger Server users can use the Administrative form in Public Folders to designate selected COM Add-ins as trusted. These trusted COM Add-ins are not subject to the limitations of the object model guard. For details regarding the Outlook E-Mail Security Update and the use of trusted COM Add-ins to customize security restrictions, see Chapter 13.

In order to avoid the Warning dialog box, use the following code to obtain the name of the CurrentUser property:

Figure 11-4. This Warning dialog box appears when you attempt to access the CurrentUser property of the NameSpace object.

The Outlook Window (Explorer Objects)

The Explorer object represents the window in which the contents of a folder are displayed. The Explorers object is the parent collection object for Explorer objects. The following sections cover some of the methods and properties for the Explorer and Explorers objects.

Figure 11-5 illustrates elements of the Outlook user interface viewed from an object model perspective. This illustration is not meant to be all-inclusive; it shows just a few of the objects in the Outlook Object Model that you can manipulate programmatically.

Figure 11-5. Object model components of the Outlook user interface

More Info   For a complete list and description of the properties, methods, and events for the Explorer and Explorers objects, see Microsoft Outlook Visual Basic Reference Help.

Import!ant   Open the Explorer object item in the VBScript! Samples folder to work directly with this code in Outlook.

Explorer Methods

Creating a new Explorer window

Outlook supports an Explorers collection object. You can use the Explorers object to add a new Explorer window for a specific folder. Use the Display method to present the new Explorer window. The following example creates a new Explorer window for the Drafts folder by using the Add method and then shows the new window on the desktop in a normal window state.

Explorer Properties

Returning the active folder

You can use the CurrentFolder property of the Explorer object to return the active folder in the Outlook window. The following example shows the name of the active folder in the message box when the DisplayTheCurrentFolder control is clicked:

Obtaining the current view for the active Explorer

You can use the CurrentView property of the Explorer object to return or set the current view for the Active Explorer window. The example on the following page displays the name of the current view for the Active Explorer window.

Determining which items are selected in the Explorer

The Selection collection object lets you know which items are selected in the Explorer window. The Selection object, in turn, contains an Items collection that lets you iterate over selected items. If you are writing VBA code, you can respond to the SelectionChange event of the Explorer object. The following example displays the number of selected items in the Active Explorer and then asks whether the user wants to display the items:

The Panes Collection Object

The Panes collection object is a property object of the Explorer object. The Panes collection object contains the three panes of the Outlook Explorer window, as shown in Figure 11-6. These are the Outlook Bar pane, the Folder List pane, and the Preview pane.

You can create an instance of an OutlookBarPane object from the Panes collection only. The Preview and Folder List panes are not accessible from the Outlook Object Model. When you navigate an Outlook Bar’s groups and shortcuts in code, you start with the Panes collection object, as demonstrated in the following code example:

Figure 11-6. Three Explorer panes comprise the Panes collection object.

Determining Whether a Pane is Visible

You can determine whether an individual pane is visible by using the IsPaneVisible method of the Explorer object. To make a pane visible, you use the ShowPane method. The following VBScript! code makes the Folder List pane visible:

Note   You cannot size panes programmatically in the Explorer window in Outlook.

The OutlookBarPane Object

The OutlookBarPane object is the only object you can instantiate from the Panes collection object. It represents the Outlook Bar as well as its groups and shortcuts. Generally, you’ll create a reference to the OutlookBarPane object as a means to access its dependent child objects that represent Outlook Bar groups and shortcuts. You can use the CurrentGroup property of the OutlookBarPane object to set or get the current group on the Outlook Bar. The OutlookBarPane object supports two important events: BeforeNavigate and BeforeGroupSwitch. These events inform you when a user is navigating to a shortcut or a group, respectively. For additional information on writing event procedures as well as the events supported by the OutlookBarPane, OutlookBarGroups, and OutlookBarShortcuts objects, see Chapter 9.

The OutlookBarStorage Object

The OutlookBarStorage object is an accessor object in the Outlook object hierarchy and has no methods or events of its own. OutlookBarStorage is used to access the OutlookBarGroups collection object through its Groups property. You can access the OutlookBarStorage object by using the Contents property of the OutlookBarPane object. The following VBA code demonstrates the use of the Contents and Groups property objects:

The OutlookBarGroups Collection Object

The OutlookBarGroups collection object is one of two critical collection objects used to program the Outlook Bar. Using the Groups object, you can add, modify, or delete groups on the Outlook Bar. The OutlookBarGroups object also supports three events that provide an additional level of programmatic control over Outlook Bar groups: GroupAdd, BeforeGroupAdd, and BeforeGroupRemove. The following example creates an Outlook Bar group named Web Links and positions it as the last group on the Outlook Bar:

Note   The Add method just shown uses named arguments to pass the name and index arguments to the Add method of the OutlookBarGroups object. You can list named arguments in any order. A named argument consists of the name of the argument, followed by a colon and an equal sign (:=), followed by the value assigned to the argument. You can also use expression!s, and the value of the expression! will be assigned to the argument.

The OutlookBarGroup Object

The OutlookBarGroup object represents a group on the Outlook Bar. You can manipulate the properties of the OutlookBarGroup object using its Name and ViewType properties. The ViewType property controls whether the shortcuts in the group display with a large or small icon. Use the Item property to access an existing member of an OutlookBarGroups collection object. The following example renames the Outlook Bar group named Web Links that we created in the previous example and changes the shortcuts to small icons. This enables the user to see more icons in the group before having to use the scroll bar to view other shortcuts.

The OutlookBarShortcuts Collection Object

OutlookBarShortcuts is a property collection object for the OutlookBarGroups object. You use this collection object to add, modify, or remove shortcuts from an Outlook Bar group. Like the OutlookBarGroups collection object, OutlookBarShortcuts supports three events you can use when you write event procedures to be executed when an Outlook shortcut has been added or removed. These events are ShortcutAdd, BeforeShortcutAdd, and BeforeShortcutRemove.

The OutlookBarShortcut Object

The OutlookBarShortcut object represents a shortcut on the Outlook Bar. A shortcut in Outlook 2000 or Outlook 2002 can launch an executable file on a local or network drive, navigate to a URL, or navigate to an Outlook folder in the folder hierarchy. The following table lists some of the common shortcuts used in Outlook 2000 and Outlook 2002.

Shortcut Function Target Property Example
Navigate to Outlook folder MAPIFolder object
Open a file system file String file URL specification
Open a file system folder String folder path specification
Open a Web page String URL

The Target property of OutlookBarShortcut determines what action occurs when a user clicks a shortcut on the Outlook Bar. Oddly enough, the Target property is read-only; when you set the Target property by adding a shortcut, you must remove the shortcut and add it again if you want to change the property.

Note   If you use an http URL as the target of a shortcut, Outlook will open the Web page as a Web View in the Outlook Explorer window. If you want to open the Web page in a separate window, right-click the shortcut in Outlook and select Open In New Window from the shortcut menu. In Outlook 2000, this action will open the URL in a new browser window. In Outlook 2002, this action will open the URL in a new Outlook Explorer window.

OutlookBarShortcut supports the new SetIcon method for Outlook 2002. Use SetIcon to set the icon for an OutlookBarShortcut object.

The CommandBars Collection Object

The ability to program the Outlook Bar gives you a significant level of control over the Outlook user interface. Using the OutlookBarGroups and OutlookBarShortcuts events, you can prevent a user from removing an Outlook Bar group or shortcut that is essential to your application. You can also dynamically add Outlook Bar groups and shortcuts. You don’t have the same flexibility, however, with Outlook Bar objects as you do with all the objects belonging to Office command bars. CommandBar and Assistant objects are actually members of the Office Object Model. CommandBar objects give you the opportunity to customize Outlook in a way that was impossible in Outlook 97 and Outlook 98. That said, the following discussion gives an overview of using command bars in Outlook. How you call CommandBar objects in Outlook differs somewhat from how you call them in other Office applications.

Note   If you are writing a COM Add-in, you must explicitly add a reference to the Microsoft Office 9.0 Object Library or Microsoft Office 10.0 Object Library using the appropriate command in your development tool. If you are using Outlook VBA to write code in the VBAProject.otm file, Outlook automatically creates a reference to the Microsoft Office 10.0 Object Library.

Overview of Command Bars

In the Outlook Object Model, both the Explorer and Inspector objects contain a CommandBars property object. The CommandBars object for Inspector and Explorer controls all Outlook toolbars, menu bars, and shortcut menus. The CommandBar object and its children contain the following items:

  • Menu bars, toolbars, and shortcut menus
  • Menus on menu bars and toolbars
  • Submenus on menus, submenus, and shortcut menus

You can modify any built-in menu bar or toolbar, and you can create and modify custom toolbars, menu bars, and shortcut menus to deliver with your Outlook VBA project or COM Add-in application. Use command bar customization to present the features of your application as individual buttons on toolbars or as groups of command names on menus. Because both toolbars and menus are command bars, you can use the same kind of controls on them.

Custom command bars differ somewhat from built-in command bars because they can be deleted from the Outlook environment. Built-in command bars can be modified by the user or by program code. However, built-in command bars can be restored to their original state and default behavior by using the Reset command button on the Toolbars page of the Customize dialog box.

The following table shows the built-in command bars in Outlook.

Object Built-In Command Bar
Explorer Menu Bar
Standard
Advanced
Remote (Outlook 2000 only)
Web
Clipboard (Outlook 2000 only)
Inspector Menu Bar
Standard
Formatting
Form Design
Clipboard (Outlook 2000 only)

Be aware that command bars are defined as either docked or, in the case of a floating command bar or menu bar, undocked. Outlook features four command bar docks—one at the left, right, top, and bottom of the Outlook window.

Outlook CommandBarButton objects represent buttons and menu items. The pop-up controls that display menus and submenus are known as CommandBarPopup objects. Both the menu and the submenu are unique CommandBar objects with their own sets of controls. In addition to CommandBarButton and CommandBarPopup objects, the CommandBarControls object can contain CommandBarComboBox objects. CommandBarComboBox objects assume a variety of different types: edit box, drop-down list box, or drop-down combo box. Like the List Box control on Outlook forms, the CommandBarComboBox object supports both an AddItem method to add items to the control and a ListIndex property to retrieve the selection index.

Exploring the CommandBars Collection

One way to learn more about the CommandBars object is to write code that maps the existing built-in and custom Outlook command bars. Because Outlook supports command bars for both the Explorer and Inspector windows, the following function requires a class argument that indicates whether the Inspector or Explorer command bars and controls should be output to the Debug window.

PrintAllCBarInfo can be found in the basCommandBars module in VBA Samples.zip in the VBA Samples folder.

To use the code in the VBA Samples folder

  1. Using Windows Explorer, expand the Building Microsoft Outlook 2002 Applications folder. Then expand the 4. Beyond the Basics folder, and then expand the Visual Basic For Applications folder, followed by the VBA Samples folder.
  2. The code, class, and user form modules for VBAProject.otm are in VBA Samples.zip in the VBA Samples folder. You can extract these items from VBA Samples.zip by using a Zip utility program such as WinZip, which is availble at http://www.winzip.com.
  3. You can also replace your current VBAProject.otm file with the VBAProject.otm installed by the setup program on the companion CD.

To run the PrintAllCBarInfo procedure

  1. Open the Visual Basic Editor by pressing Alt+F11.
  2. Extract basCommandBars from VBA Samples.zip in the VBA Samples folder to a file system folder.
  3. Select Import! File on the File menu to import! basCommandBars into your Outlook VBAProject.otm.
  4. Press Ctrl+G to open the Debug window.
  5. Type ?PrintAllCBarInfo(olExplorer), and press Enter. Information on all command bars and controls in the CommandBars collection will display in the Debug window.

The following function is a helper function for the CBPrintAllCBarInfo function just shown. This function calls two other functions that enumerate the types of command bars and command bar controls. See the code in the basCommandBars module for a complete listing.

Listed next you’ll find the output of CBPrintCBarInfo as it appears in the Debug window. This excerpt shows all the controls on the Outlook Advanced toolbar.

Using Images on Command Bar Buttons

Once you have explored the Outlook command bars and their controls, take a look at the images used on these buttons. If you plan to write code to create your own custom command bars, you need to find a source for icons that will appear on the buttons. You can use the FindControl, CopyFace, and PasteFace methods to copy and paste images from a built-in button to custom buttons you’ve created. You can also supply a FaceID value for your custom command bar button that corresponds to the FaceID for a built-in icon. The following procedure creates a temporary custom toolbar that displays built-in Office icons, as shown in Figure 11-7 (on page 443). If you hold your mouse pointer over the button, a tooltip will display the FaceID property.

To run the CBShowButtonFaceIDs procedure

  1. Open the Visual Basic Editor by pressing Alt+F11.
  2. Drag basCommandBars from the VBA Samples folder to a file system folder such as C:\My Documents.
  3. Select Import! File on the File menu to import! basCommandBars into your Outlook VBAProject.otm.
  4. Press Ctrl+G to open the Debug window.
  5. Type ?CBShowButtonFaceIDs(0, 299, olExplorer), and press Enter.
  6. Press Alt+F11 to return to the Outlook application window. You should see the ShowFaceIDs toolbar displayed over the Explorer window.

Figure 11-7. The ShowFaceIds toolbar provides a palette of images to use for custom buttons.

Use the ShowFaceIDs toolbar to provide icon images for your custom toolbar buttons. Place the cursor over the desired command button to learn its FaceID property. You can copy the code for the cmdNewButton object shown a moment ago and paste it into the code that your own button creates. Just substitute the actual value for the FaceID icon that you need for the intCntr variable.

Adding a Command Bar to the Collection

Use the Add method to add a command bar to either the Inspector or the Explorer CommandBars collection. If you are using Visual Basic rather than VBScript!, you can use named arguments when you call the Add method of the CommandBars collection object to add a command bar. The following example adds the Items command bar to the Explorer CommandBars collection:

In VBScript!, all variables are declared as Variants and named arguments are illegal. Here is a statement that adds an Inspector command bar:

The Position property determines whether the toolbar will be docked in the Explorer or the Inspector window or displayed as a floating toolbar. If you supply the msoBarPopUp value for the Position argument, you will create a shortcut menu rather than a menu bar or toolbar. The following table shows the possible values for the Position property.

Constant Description
msoBarLeft=0, msoBarTop=1, msoBarRight=2, msoBarBottom=3 Indicates the left, top, right, and bottom coordinates of the new command bar
msoBarFloating=4 Indicates that the new command bar won’t be docked
msoBarPopup=5 Indicates that the new command bar will be a shortcut menu

The Temporary property indicates whether the command bar will be deleted when the Outlook application or the Inspector window closes. Notice that the VBScript! Command Bar Example toolbar is temporary; it appears only for a specific custom form. Generally, you don’t want to create persistent Inspector toolbars.

Note   Once you have added the command bar to the CommandBars collection, you can set additional properties that determine the command bar’s appearance and behavior. For example, the Type property determines whether the CommandBar object behaves as a menu bar, toolbar, or shortcut menu.

Retrieving an Existing Command Bar

To retrieve an existing built-in or custom command bar, use the Items property with either an index value or the name of the command bar. Because the Items property is the default property of the CommandBars collection object, you don’t actually have to use the Items property to retrieve a command bar from a collection. The following two statements are equivalent:

Deleting a Command Bar

Use the Delete method to delete a custom command bar from the CommandBars collection. You cannot delete a built-in command bar with the Delete method. The Delete method is actually a CommandBar method, not a CommandBars method. The following function deletes a command bar and returns True if the command bar was successfully deleted:

Using the OnUpdate Event

The CommandBars collection supports an OnUpdate event that fires whenever a command bar is changed. For additional information regarding Visual Basic events, the WithEvents keyword, and event procedures, see Chapter 9. The event is triggered by any change to a command, or by the state of a bar or command bar control. These changes can result from pressing a button, by changing text, or by selecting a cell. Because a large number of OnUpdate events can occur during normal usage, you should be very cautious when working with this event. I strongly recommend that you use this event primarily for checking that a custom command bar has been added or removed by an Outlook COM Add-in. To see how many times this event can fire, add the following code to VBAProject.otm. A statement appears in the Debug window every time the OnUpdate event fires.

The CommandBar Object

The CommandBar object represents a command bar—either built-in or custom—for either the Outlook Explorer or Inspector window. You can modify a built-in command bar through the Customize dialog box or through program code. If you are building a custom Outlook application or creating a COM Add-in, you should consider providing a custom command bar or modifying the menus on the Outlook menu bar for your COM Add-in. Once you have created a command bar object programmatically, you should add controls to the command bar and program them to respond to events such as Click or Change.

Properties of the CommandBar Object

The following table lists some important properties of the CommandBar object. For additional information on CommandBar object properties, see Microsoft Outlook Visual Basic Reference Help.

Property Description
AdaptiveMenus Determines whether an individual command bar displays adaptive menus. This property can be True or False.
Enabled Determines whether the command bar can be modified with the Customize dialog box. If the Enabled property is False, you cannot set the Visible property to True.
Position Returns or sets the position of the command bar.
Type Determines the type of command bar—menu bar, toolbar, or shortcut menu.
Visible Determines whether the command bar is visible in the Explorer or Inspector window. This property can be True or False.

Methods of the CommandBar Object

The methods listed in the following table operate on the CommandBar object. For additional information on methods for the CommandBar object, see Microsoft Office Visual Basic Reference Help.

Method Description
Delete Deletes a custom command bar.
FindControl Finds a control on a command bar that meets specified criteria. You can search by control type, ID, or tag property based on whether a control is visible or on a submenu.
Reset Resets a built-in command bar to its default configuration. If you have customized a built-in command bar, those customizations are removed when you call this method.
ShowPopup Shows the command bar as a pop-up menu at specified coordinates or at the current cursor location.

The ShowPopup method will work only for a command bar that has been added as a shortcut menu to the CommandBars collection. You cannot cause a built-in or custom toolbar to appear suddenly as a pop-up menu. The Outlook Inspector has a limited capacity to display shortcut menus because a MouseUp event is not supported using the current control container for Outlook custom forms. If you are utilizing UserForms in your VBA or COM Add-in project, use the MouseUp event of intrinsic and third-party ActiveX controls to build event procedures that display Outlook shortcut menus. The following procedure displays a pop-up menu at the current cursor location in the Explorer window:

The next procedure uses the MouseUp event to display the Data Helper shortcut menu when the right mouse click occurs over the lstSync control on a UserForm:

Protecting a Command Bar from User Modification

How do you protect a custom command bar you’ve developed from user modification? A user can modify your command bar either through the user interface or through program code. To prevent changes to your custom command bar, you can set the Enabled property to False to make the command bar invisible in the list of Outlook command bars for either the Explorer or Inspector window. Once the Enabled property is set to False, users cannot modify your custom command bar because they will not be able to see the command bar name in the Toolbars list. You must reset the Enabled property to True before you can use the Visible property to display the command bar. However, the Enabled property is not the most secure means of protecting your custom command bar. The following procedure can prevent a user from using the Customize dialog box to alter your custom command bar. The code disables the Customize command on the Tools menu and the Toolbars list on the View menu.

The CommandBarControls Collection Object

CommandBarControls is a collection object that represents all the controls on a command bar. You use the Controls property of a CommandBar object to refer to a control on a command bar. The Controls property is a CommandBarControls collection. If the control is of the type msoControlPopup, it also will have a Controls collection representing each control on the pop-up menu. Pop-up menu controls represent menus and submenus and can be nested several layers deep, as shown in the second example in this section.

In the following example, the code returns a reference to the New button on the Standard toolbar and displays the type of the control in a message box:

Here, the code returns a reference to the Macros control on the Macro pop-up menu located on the Tools menu on the menu bar for the Explorer window:

Because each pop-up menu control is actually a CommandBar object, you can also refer to it directly as a member of the CommandBars collection. For example, the following line of code returns a reference to the same control as the previous example did:

Once you have a reference to a control on a command bar, you can access all available properties and methods of that control.

Note   When you refer to a command bar control by using the control’s Caption property, you must specify the caption exactly as it appears on the menu. For example, in the previous code sample, the reference to the control caption “Macros. . .” requires the ellipsis (. . .) in order to match the way the caption appears on the menu. However, you do not have to include the ampersand (&) that is returned in the control’s Caption property when you refer to the control. Controls(“Macros . . .”) is equivalent to Controls(“&Macros . . .”) in the previous example.

Use the Count property of the CommandBarControls collection to return the number of controls in the collection object. To add controls to the collection, use the Add method. The Item property is the default property of the CommandBarControls collection object. For this reason, you do not have to use the Item property to access individual controls in the collection if you are writing Visual Basic or VBA code. Controls(“Macros…”) is the equivalent of Controls.Item(“Macros…”). However, if you are writing VBScript! code, you must use the Item property to access individual controls in the collection.

The CommandBarControl Object

The CommandBarControl object is the child object of the CommandBarControls object, and it represents a control on a built-in or custom command bar. If you want to refer to a control on a built-in command bar, you should dimension the control variable as a CommandBarControl object. If you want to instantiate an object on a custom command bar, use the CommandBarButton, CommandBarComboBox, or CommandBarPopup object for your item declaration in Visual Basic. If you are using VBScript! in an Outlook form, the type of the object is immaterial because all objects are Variants by default.

Note   If you do declare a control object as a CommandBarControl, you can still use the properties and methods of the CommandBarButton, CommandBarComboBox, and CommandBarPopup objects with it. However, dimensioning the control as the correct variable type is the preferred approach. You cannot use the read-only Type property to change the type of an existing custom control. If you want to change the control type, you must delete the control and then add it with the correct type argument in the Add method of the CommandBarControls object.

Adding Custom Command Bar Controls

The CommandBarControl object allows you to modify built-in controls or to add new controls on a custom command bar. Additionally, you can set the properties of the control to determine how the control will appear or what procedure will run when the user clicks the command button or selects a menu item. The difference between CommandBarControl objects is clearly demonstrated in the following code sample for a command bar named Testing. The Testing command bar, shown in Figure 11-8, uses every type of control available for a custom command bar.

Figure 11-8. The Testing command bar

The code required to create Testing is relatively straightforward. It’s presented in sections so that you can clearly understand each step of the coding process. The first order of business is to instantiate a CommandBar object so that controls can be added to the command bar’s CommandBarControls collection. The next line attempts to instantiate a Testing CommandBar object from theExplorer’s CommandBars collection. If Testing already exists and no error occurs, the existing toolbar is deleted before the command bar is added.

Notice that we’ve added a position argument to the Add method in order to place the command bar in the top dock. Now we’re ready to add controls to the command bar. These additional controls don’t actually do anything when clicked. Four different types of controls will be added to Testing. The first is a standard button that’s typical of the controls on toolbars. We’ve assigned the caption Color to this button and an icon that corresponds to the built-in FaceID 2167, the icon for the color palette. In order for both the icon and the caption to appear, you must set the button’s style to msoButtonIconAndCaption. If you are using a built-in FaceID to provide an icon for a custom button, you must set the button’s Visible property to True or the icon will not appear, even though the new button appears on the toolbar.

The next control to add to Testing is an Edit box control. Edit box controls are equivalent to edit boxes on an Outlook form. A separate object type does not exist for edit controls. Edit box controls are actually CommandBarComboBox objects. Their Type property is msoEditBox. Edit box and List box controls can show a label before the control if their Style property is set to msoComboLabel. The following code adds an Edit box control to Testing and sets its Text property to Red:

The ComboBox control uses many of the same properties and methods as the MSForms combo box that you’re familiar with from Outlook forms. You can use the AddItem method to add items to the list and the ListIndex property to set or return the selected item in the list. Like the Edit box control, this combo box uses a caption to identify the value being selected by the user.

Finally we’ll add a Popup control to Testing and make the toolbar visible. Remember that every Popup control contains a Command Bar object and a corresponding controls collection. If you want to add items to the Popup control, use the Add method for the Controls property object of the CommandBarPopup object. The following code adds three button controls to the Popup control. If we added these controls as Popup controls rather than button controls, we would have submenus that could contain additional submenus or button controls.

Note   The last statement in the previous code listing makes the new custom command bar visible. Unless you set the Visible property of your custom command bar, you will not be able to see the new command bar in the Outlook Explorer or Inspector window.

Running a Procedure for a Control

Adding controls to your custom toolbar is not very useful unless they help the user perform an action. To run a procedure when a user clicks a control button or a combo box changes, you can set the OnAction property to refer to a Sub procedure or Function procedure in your project. If you are creating a custom command bar in an Outlook form using VBScript!, using the OnAction property is the only way you can run a procedure for a control. If you are creating a COM Add-in, you also have the option to declare the object variable for the control using the WithEvents keyword and run an event procedure when the control’s Click event (CommandBarButton) or Change event (CommandBarComboBox) fires.

The following code from the Items toolbar example will cause the LaunchWordMail procedure to run when a user clicks the HTML Word Mail icon on the Items toolbar:

Note   If you have more than one procedure with the name LaunchWordMail in different code modules, none of the procedures will run when the button is clicked. Outlook must be able to resolve the procedure name specified in the OnAction property for the procedure to run correctly. You cannot use traditional basOutlook.LaunchWordMail syntax to call a procedure in a specified module.

An equivalent OnAction property exists for the CommandBarComboBox controls. Combo box controls run the OnAction procedure when a change event fires. Button controls run the OnAction procedure when a Click event fires. If the Change event causes the OnAction procedure to run, you can examine the ListIndex property of the control to determine the combo box item selected by the user.

If you have multiple controls that point to the same procedure in their OnAction property, use the Parameters property of the control to determine whichcontrol has been clicked. You set the Parameters property of the control when you add the control to its command bar. The ActionProperty of the CommandBar object returns an object representing the control that has been clicked or changed. This example shows how you can use the Parameter and ActionControl properties to branch code execution depending on the Parameter property:

Showing and Enabling Controls

Use the Visible property of a control to show or hide the control on a command bar. Use the Enabled property to enable or disable the control on the toolbar. When a control is disabled, it is still visible but the user cannot perform an action on it. The following function toggles the state of a command bar control. To test this function, type ?CBCtlToggleVisible(“Tools”, “&Options…”) in the Debug window and press Enter to toggle the Enabled property of the Options command on the Explorer Tools menu.

The Visible property is not the only factor that determines whether a specific menu item is visible on a given menu. If personalized menus are turned on with the AdaptiveMenus property, you can use the IsPriorityDropped property to determine whether a menu item is visible on the command bar. If the control’s Visible property is set to True, the control will not be immediately visible on a personalized menu if IsPriorityDropped is True.

Note   To determine when to set IsPriorityDropped to True for a specific menu item, Outlook counts the number of times the menu item was used and records the different application sessions in which the user employs another menu item in the same menu as this menu item, without using the specific menu item itself. When this value reaches a threshold, the count is decreased. When the count reaches zero, IsPriorityDropped is set to True. You cannot set the session value, the threshold value, or the IsPriorityDropped property. You can, however, use the AdaptiveMenus property to disable adaptive menus for specific menus in an application.

Determining the State of a Control

The State property of a control tells you whether a button control is in the down or up position. The State property is read-only for built-in controls. A good example of a built-in control that displays state is the Folder List control on the Advanced toolbar. When the control’s state equals msoButtonDown, the button is depressed on the toolbar. If the control’s state equals msoButtonUp, the button is not depressed on the toolbar. This code examines the state of the Folder List button on the Advanced toolbar:

Adding Separators Between Controls

If you want to add a separator between buttons on a command bar, set the BeginGroup property for the control to True. Group separators on a toolbar provide important visual clues for the user about the relationship of controls. The following example adds a group separator before the Choose Form control on the Items toolbar:

Finding a Control

To find a control on a built-in or custom command bar, use the FindControl method. The FindControl method takes several arguments that facilitate your search. The following example performs a nonrecursive search of the Standard toolbar for the Find A Contact combo box. If a control with a type of msoControlComboBox is found on the Standard toolbar and that control’s caption is Find A Contact, the Text property of the combo box is set to the name of a contact. Setting the combo box Text property causes Outlook to search for the contact name as though a user had actually typed a name into the combo box. If the search completes successfully, Outlook displays the Inspector for the contact item.

Using Control Events

Command bar controls raise two separate events: Click and Change. You can use these events in place of the OnAction property to run an event procedure when a user action or program code causes an event to fire. The table on the following page displays the control and command bar events.

Event Source Object Occurs
OnUpdate CommandBars When any change occurs to a built-in or custom command bar, or to the state of a control on a command bar.
Click CommandBarButton When a button or menu item is clicked.
Change CommandBarComboBox When a user makes a selection in a drop-down list box or a combo box. The Change event also occurs when text is changed in an edit box.

More Info   Be aware that you cannot use control events when writing VBScript! code in an Outlook custom form. In this case, you must use the OnAction property to specify the Sub procedure in your code that runs when a toolbar button is clicked.

To write an event procedure for a command bar control

  1. Declare an object variable by using the WithEvents keyword in the declarations section of ThisOutlookSession or in the class module for your COM Add-in project.
  2. Select the object in the Object box of the class module’s code window.
  3. Select the event name in the Procedure box of the class module’s code window.
  4. Write event procedure code to respond to the Click or Change event.

The CommandBarButton Object

The CommandBarButton object represents a button control on a command bar. We have already discussed in detail many of the properties and methods of the CommandBarButton object. For additional information, search for CommandBarButton in Outlook Visual Basic Reference Help. The Outlook 2000 and Outlook 2002 Explorer and Inspector command bars offer major improvements over command bars in previous versions of Outlook. You can create custom command bars for an Inspector in a previous version of Outlook if you use the Office 97 CommandBars object. However, custom command bars in Outlook 97 and Outlook 98 do not persist between Outlook sessions and cannot be created for the Explorer window. You can use the Execute method to cause built-in commands to run, but the functionality and customization potential of toolbars is limited in previous versions of Outlook.

Note   For additional information regarding command bars in previous versions of Outlook, see the following articles in the Microsoft Knowledge Base:

The CommandBarComboBox Object

The CommandBarComboBox object represents a Combo box or an Edit box control on a command bar. When you add the combo box to a command bar, you specify the type of combo box in the Add method. The following table lists some of the unique properties, methods, and events of a CommandBarComboBox object.

Type Name Description
Property DropDownLines Returns or sets the number of items displayed in the drop-down list box. If the number of items in the list is greater than DropDownLines, a scroll bar appears in the drop-down list box.
DropDownWidth Returns or sets the width in pixels of the combo box drop-down.
ListCount Returns the number of items in the list.
ListIndex Returns or sets the index of the selected item in the list.
Text Returns or sets the text in the edit portion of the control.
Method AddItem Adds an item to the list.
Clear Clears the items in the list.
RemoveItem Removes an item from the list.
Event Change Occurs when a user changes the selection in a combo box or the text in an edit box.

The CommandBarPopup Object

The CommandBarPopup object represents a pop-up control on a command bar. Pop-up controls are unique in that every control contains a CommandBar property object. You can use the CommandBar object to access the child controls of a CommandBarPopup object. The following example uses the CommandBar property object to add additional buttons to the pop-up control:

The AddressLists Collection Object

Outlook users often have several address books from which they can select recipients for a message. The AddressLists collection object contains all the address books available to a user. Using the AddressLists object, you can reference one or more AddressList objects, each of which represents a single address book.

Import!ant   Open the AddressLists collection object, AddressEntries collection object, and the AddressEntry object items in the VBScript! Samples folder to work directly with this code in Outlook.

The AddressLists collection object is always referenced from the NameSpace object.

AddressLists Collection Methods

This section covers the Item method of the AddressLists collection object.

Iterating through a collection of address lists

You can use the Item method of the AddressLists collection object to iterate through a collection of address books. The following example uses the Count property of the AddressLists collection object to determine the number of AddressList objects referenced by the collection. It then uses the Item method of the AddressLists collection object to return and display the name of each address book.

The AddressList Object

The AddressList object represents a single Outlook address book that contains a set of AddressEntry objects. The AddressEntry objects, in turn, can be accessed through the AddressEntries property of the AddressList object.

Outlook Security   If your code attempts to access an AddressEntries collection object or an AddressEntry object, the Warning dialog box shown in Figure 11-4 (on page 429) will be displayed. See Chapter 13 for methods to eliminate the Warning dialog box.

The AddressEntries Collection Object

The AddressEntries collection object is provided by the AddressEntries property of the AddressList object. It provides access to each of the AddressEntry objects contained within a given address book.

AddressEntries Collection Methods

This section covers the Add and Item methods of the AddressEntries collection object.

Adding an address entry

You can use the Add method of the AddressEntries collection object to create a new item in an address book. The following example uses the Add method to create a new entry in the Personal Address Book. The Update method of the AddressEntry object is required to commit the new item to the address book.

Iterating through a collection of address entries

You can use the Item method of the AddressEntries collection object to iterate through the items in an address book. The following example uses the Count property of the AddressEntries collection object to return the number of items in the user’s Personal Address Book. It also uses the Item method of the AddressEntries collection object to return each item in the address book and then display its name.

The AddressEntry Object

The AddressEntry object represents an individual item in an address book. The AddressEntry object contains information about one or more individuals or processes to which the messaging system can send messages. If the AddressEntry object represents a distribution list—that is, if its DisplayType property is set to olDistList or olPrivateDistList—it can contain additional AddressEntry objects that can be accessed through its Members property.

AddressEntry Object Methods

This section covers the Details, Update, Delete, and GetFreeBusy methods of the AddressEntry object.

Displaying details of an address entry

The Details method of the AddressEntry object displays a modal dialog box that lets a user see (and, if permissions allow, change) the information stored in the Address Book item represented by the object.

The following example steps through the items in a user’s Personal Address Book, using the Details method to display the information contained in each item. If the user clicks OK in the dialog box, the next entry is displayed. If the user clicks the Cancel button in the dialog box, an error is produced. For this reason, an On Error statement is included to prevent the routine from exiting immediately, and the Err global variable is tested to determine if it is not zero (which would indicate that the user clicked Cancel or that an error had occurred).

Changing an address entry

If you have the appropriate permissions, you can change the Address, Name, and Type properties of an AddressEntry object. To commit the change to the address book, you use the object’s Update method. The following example converts the Name property of an AddressEntry object to all uppercase characters:

Deleting an address entry

The Delete method of the AddressEntry object removes an item from the address book. The following example steps through the items in the Personal Address Book and deletes the first item where the type is set to Sample:

Getting free/busy information for a user

You can determine whether someone is available at a given time using the GetFreeBusy method of the AddressEntry object. This method returns a string representing 30 days of free/busy information starting at midnight on a specified date. Each character in the string is a digit that indicates whether the person is available during a specified time period. You can specify that the string should indicate only whether the person is available, or you can specify that you want the string to indicate whether a busy time is marked as tentative or out of office.

For example, the following code example returns a string 1440 characters long (48 half-hour periods over 30 days) containing 0 for each half-hour period the person is free, 1 for each period the person has a busy time marked tentative, 3 for each period the person has a busy time marked out of office, and 2 for other busy periods:

The following code example returns a string 720 characters long (24 one-hour periods over 30 days) containing 0 for each hour the person is free and 1 for each hour the person is busy, regardless of how the busy periods are designated:

The following example displays the next time a person is busy. In addition to Outlook objects and methods, it uses the following VBScript! functions:

  • InputBox To prompt the user for the name of the person whose first busy time is to be checked.
  • Date To retrieve the current date.
  • FormatDateTime To convert the retrieved date to the format required by GetFreeBusy.
  • InStr To determine the location (offset) of the first 1 character in the string returned by GetFreeBusy.

AddressEntry Properties

You can use such properties as Name, Address, Members, Type, and Manager to retrieve useful information contained in the item.

More Info   For a complete list and description of the methods and properties for the AddressEntry object, see Microsoft Outlook Visual Basic Reference Help.

The following example uses the Members, Name, and Address properties of the AddressEntry object to display the name and address of each member of a private distribution list named Department:

Using CDO to Obtain Recipients

Collaboration Data Objects (CDO) is an object model that assists in building messaging and collaboration applications. CDO serves as a complementary object model to manipulate MAPI folders and items from Visual Basic or VBScript! code. You can use CDO to access messaging objects which are not available in the Outlook Object Model. For example, the Address procedure shown next lets you present an AddressBook dialog box to the user. When the user makes recipient selections from the AddressBook dialog box, the resolved recipient names are stored in the user-defined field CDORecipients on the AddressEntry object example form in the VBScript! Samples folder.

Outlook Security   Access to Recipients, AddressEntries, and AddressEntry objects is also blocked in the CDO Object Model by the Outlook E-Mail Security Update component of Outlook 2002. Unlike blocked Outlook objects, properties, and methods, you cannot create trusted CDO code that eliminates the Warning dialog boxes using the Administrative form in public folders. However, there are third-party alternatives for accessing CDO properties, methods, and objects in a trusted context.

Installing Collaboration Data Objects

Unfortunately, CDO is not installed by default with Outlook 2002. This practice reverses Microsoft’s default CDO installation for Outlook 98. CDO provides functionality for many of the examples in this book and must be installed for the examples to operate correctly. The setup program for the companion CD automatically installs CDO, or CDO can be installed manually.

To install Collaboration Data Objects

  1. Insert the Office XP CD-ROM into your CD-ROM drive.
  2. Click Start, click Settings, and then click Control Panel.
  3. Double-click Add/Remove Programs.
  4. On the Install/Uninstall page, click Microsoft Office XP and then click Add/Remove.
  5. In the Microsoft Office XP Maintenance Mode dialog box, click Add Or Remove Features.
  6. Double-click the Microsoft Outlook For Windows item to expand the item in the Microsoft Office XP: Update Features dialog box.
  7. Click the Collaboration Data Objects item under Microsoft Outlook For Windows to expand the item.
  8. Select Run From My Computer.
  9. Click Update Now to complete the installation of Collaboration Data Objects.

The Folders Collection Object

The Outlook Object Model provides two folder objects: a Folders collection object and a MAPIFolder object. The Folders collection object represents multiple folders. The MAPIFolder object, covered later in this chapter, represents a single folder.

The Folders collection object can contain single or multiple folders. The Folders collection object is always referenced from the NameSpace object.

More Info   For a complete list and description of the properties, methods, and events for the Folders collection object, see Microsoft Outlook Visual Basic Reference Help.

Folders Collection Methods

This section covers the Add and Item methods of the Folders collection object.

Adding a folder to the folder list

You can use the Add method of the Folders collection object to add a folder to the Folder List. The following example uses the Add method of the Folders collection object to add a folder called My New Folder to the Building Microsoft Outlook 2002 Applications personal folder (.pst) file:

Iterating through a collection of folders

You can use the Item method of the Folders collection object to iterate through a collection of folders. The following example uses the Count property of the Folders collection object to return the number of folder items in the Folders collection. It also uses the Item method of the Folders collection object to return each folder in the collection and then display its name. You can also use the For Each . . . Next syntax to iterate over the objects in a collection object.

Note   When iterating through a collection of folders or items, the folders or items are not always ordered in the collection based on the date they are received in the folder. If your code depends on a particular order in the collection, use the Sort method of the collection object to control the order of the collection.

The MAPIFolder Object

The MAPIFolder object represents a single Outlook folder. A MAPIFolder object can contain other MAPIFolder objects, as well as Outlook items. This section explains how to move through the Folder List by using the MAPIFolder object and its Folders property.

More Info   For a complete list and description of the properties, methods, and events for the MAPIFolder object, see Microsoft Outlook Visual Basic Reference Help.

Import!ant   Open the MAPIFolder object item in the VBScript! Samples folder to work directly with this code in Outlook.

MAPIFolder Object Methods

This section covers the CopyTo and Display methods of the MAPIFolder object.

Copying a folder

You can use the CopyTo method of the MAPIFolder object to create a copy of a folder in another folder. The following example copies the Notes folder to the Inbox:

Displaying a folder

You can use the Display method of the MAPIFolder object to display the folder represented by the MAPIFolder object, as shown here:

MAPIFolder Object Properties

This section covers the DefaultMessageClass, FolderPath, Folders, InAppFolderSyncObject, Items, Parent, Child, EntryID, StoreID, UnReadItemCount, and WebViewURL properties. The Folders property is useful for accessing a folder in the folder list. The Items property is useful for retrieving a collection of items in the folder.

Referencing a folder in the folder list

You can use the Folders property with the MAPIFolder object to return another MAPIFolder object. The OpenMAPIFolder function shown on page 473 is a more efficient way to return a folder in the folder list, compared with the folder-by-folder method illustrated here. In the following procedure, the Folders property is used to move through the various branches of a personal folders list:

Iterating through a collection of items in a folder

You can use the Items property of the MAPIFolder object to return a collection of items in the folder. The following example uses the Items property of the MAPIFolder object to return the collection of items in the Inbox folder. It then shows the Subject value of the first five items in the Items collection.

The EntryID and StoreID properties

The EntryID and StoreID properties of the MAPIFolder object can be used to identify a folder in Outlook. The EntryID property corresponds to the MAPI property PR_ENTRYID. When an object is created, MAPI systems assign a permanent, unique ID string which does not change from one MAPI session to another. The EntryID and StoreID properties, which are analogous to primary keys in a database table, let you identify both Folder and Item objects in the MAPI subsystem. Once you have these values, you can use the GetFolderFromID method to return a MAPIFolder object.

The following example displays the value of the MAPI EntryID and StoreID for the current folder in a message box, displays another message box showing the folder’s UnReadItemCount, DefaultMessageClass, and WebViewURL, and then uses the GetFolderFromID method to re-instantiate the Folder object and display the folder:

Making a folder available for offline use

You can programmatically make a folder available for offline use by using the InAppFolderSyncObject property. Somewhat mysteriously named, the InAppFolderSyncObject property determines whether the folder will be added to the Application Folders Send/Receive group. For additional information on Send/Receive groups and offline use, see Chapter 8, “Folders.” The following code example adds the Top Accounts folder to the Application Folders group and starts a synchronization programmatically:

Returning a folder from a folder path

The OpenMAPIFolder procedure allows you to return a MAPIFolder object if you supply a folder path as an argument. A folder path is expressed as follows:

Note   The type declarations have been commented out in the OpenMAPIFolder and GetFolderPath functions. If you want to use these functions in VBA or Visual Basic code, remove the comment marks.

Returning a folder path from a folder

If you are using a version of Outlook prior to Outlook 2002, the GetFolderPath function allows you to return a string representing a folder path if you supply a MAPIFolder object as an argument. If you are using Outlook 2002, you simply use the FolderPath property of the MAPIFolder object to return a string that contains the folder path.

Displaying a folder Web view

One of the exciting features of Outlook is the ability to display Web views in the Explorer View pane. The following example sets the WebViewURL for your Drafts folder to the MSDN Online Exchange Developer Center and then displays the Web view of the folder. The WebViewOn property is then set to False to restore the default view on the folder.

New Outlook 2002 Folder Properties

In addition to the InAppFolderSyncObject property discussed previously, Outlook 2002 adds some MAPIFolder properties that are worth noting. The ShowAsOutlookAddressBook property determines whether a Contacts folder will be displayed as an Outlook Address Book. If the folder is not a Contacts folder, setting the property has no effect. The AddToPFFavorites property adds a public folder to the Favorites folder so that it’s available for offline use. The following example adds a folder named Classified Ads to the Favorites folder:

The Views Collection Object

The Views collection object, which is new in Outlook 2002, is a property object of the MAPIFolder object. You can use the Views collection object to enumerate the Views in a folder or to obtain a child View object and change the View programmatically. You can also use the Add method to add a View to a folder. The following example creates a View named Larger View in the CurrentFolder object of the ActiveExplorer object. For a more thorough explanation of modifying Views programmatically with the XML DOM (eXtensible Markup Language Document Object Model), see the Outlook View Wizard example in Chapter 14.

The Items Collection Object

Items are the discrete packages of information represented by a Mail Message, a Post item, a Contact item, a Distribution List item, a Document item, a Journal item, a Meeting Request, a Note, or a Task item. You use the Items property to return the Items collection of a MAPIFolder object. The single item object is represented by the following objects:

  • AppointmentItem object An Appointment item.
  • ContactItem object A Contact item.
  • DistListItem object A Distribution List item.
  • DocumentItem object A Document item.
  • JournalItem object A Journal item.
  • MailItem object A Mail Message item.
  • MeetingItem object A Meeting item.
  • NoteItem object A Note item.
  • PostItem object A Post item.
  • ReportItem object A Mail delivery report item.
  • TaskItem object A Task item.
  • TaskRequestAcceptItem An item sent to accept a Task request.
  • TaskRequestDeclineItem An item sent to decline a Task request.
  • TaskRequestItem An item sent to assign a Task.
  • TaskRequestUpdateItem An item sent to update a Task request.

This section covers some of the methods and properties of the Items collection object. Sections that follow this section—beginning with “The PostItem Object” on page 481—cover the methods and properties of specific Item objects.

More Info   For a complete list and description of the properties, methods, and events for the Items collection object, see Microsoft Outlook Visual Basic Reference Help.

Import!ant   Open the Items collection object item in the VBScript! Samples folder to work directly with this code in Outlook.

Items Collection Object Methods

This section covers the Add, Find, and Restrict methods of the Items collection object.

Creating a custom item

With Outlook, there are two basic methods of creating items. Standard items such as Message items (IPM.Note), Post items (IPM.Post), and Contact items (IPM.Contact) are created using the CreateItem method of the Application object, as discussed earlier in this chapter.

To create custom items, however, such as an IPM.Post.Product Idea item, you use the Add method of the Items collection object. For example, to create a Product Idea item (IPM.Post.Product Idea) for the Product Ideas folder, you must first return the Items collection object, and then use the Add method of the Items collection object to add the new item to the collection. The custom item has the methods and properties of the item upon which is it based. For example, an item with the message class IPM.Post.Product Idea contains the methods and properties of the PostItem object, in addition to the custom UserProperties defined for IPM.Post.Product Idea. If you create an item with the message class IPM.Note.Orders, you use the MailItem object.

Import!ant   Before you can create a custom item, the form associated with the item must exist in the forms library of the folder in which the item is created. For example, to create a Product Idea item, the Product Idea form must exist in the Product Ideas Folder forms library or in the Personal or Organizational Forms Libraries.

The following example references the Product Ideas folder and then creates a Product Idea item and displays it. Note that the Product Idea form exists in the Product Ideas folder forms library.

Import!ant   Note that in the preceding procedure, the Body property of the single Item object corresponds with the Message field on the form. For more details about the properties of standard items, see “MailItem and PostItem Objects Properties” later in this chapter.

Finding an item in a folder

You can use the Find method of the Items collection object to find an item in a folder based on the conditions you specify.

Import!ant   If you are using user-defined fields as part of a restriction argument of a Find or Restrict method, the user-defined fields must exist in the folder; otherwise, the code will raise an error and the Find or Restrict method will fail. You can add a field to a folder by displaying the Field Chooser and clicking New.

The following example uses the Find method of the Items collection object to return the first item in the Product Ideas folder with the value Boating in the Product Category field:

Creating a filtered collection of items from a folder

You can use the Restrict method of the Items collection object to create filters that return only those items in a folder matching the conditions you specify.

More Info   For more information about constructing filter expression!s, see Find Method and Restrict Method in Microsoft Outlook Visual Basic Reference Help.

The following example returns the collection of items from the Product Ideas folder and then creates a filtered collection of items with only the value Boating in the Product Category field:

Note   The Restrict method does not offer optimal performance for a large collection of items in a folder. If you need to iterate over hundreds or thousands of items in a folder, use the SetColumns method to cache specified properties and increase performance. Only certain Item properties can be cached with the Restrict and SetColumns methods. User-defined properties cannot be cached with SetColumns. See Restrict Method and SetColumns Method in Microsoft Outlook Visual Basic Reference Help for additional information.

Sorting the items in a filtered collection

If you want to sort the items in the Items collection, use the Sort method. Currently, the Sort method only supports sorting on built-in properties for the Item. The example below creates a restricted collection of Contacts in your mailbox that have an Email1Address value. After the restriction has been created, the Sort method is used on the filtered Items collection object. Finally the first item is the Sorted Items collection is displayed.

Import!ant   The Sort method will return an error if you attempt to sort for built-in multi-valued properties such as Companies and Categories. You also cannot sort by a user-defined field unless the user-defined field is defined in the folder. The Sort method is effective, from a performance standpoint, only for small collections of items.

Deleting the items in a collection

If you want to delete items from an Items collection object, you can’t use the For i = 1 to MyItems.Count . . . MyItems.Item(i).Delete . . . Next routine or the For Each myItem in MyItems . . . myItem.Delete . . . Next routine you would normally use to iterate over the items in the collection. The following example is a generic function that will delete all the items in the Items collection passed as an argument to the function:

Items Collection Object Properties

This section explains how to use the Count property.

Returning the count of items in the items collection

You can use the Count property of the Items collection object to return the number of items in the Items collection. This provides an easy way to loop through collections to process a large number of items, as shown in the previous example. The following example returns the number of items in the Inbox and shows the number in a message box:

The PostItem Object

The PostItem object represents a message posted in a public folder. Unlike a MailItem object, a PostItem object is not sent to a recipient. This section covers some of the methods of the PostItem object. Properties of the PostItem object are similar to the properties of the MailItem object, so they are discussed together in “MailItem and PostItem Objects Properties” later in this chapter.

PostItem Object Methods

The PostItem object provides a variety of methods that you can use to control the actions of an item. This section covers the Copy, Move, Delete, Display, and Post methods.

Copying and moving an item

You can use the Copy method of the PostItem object to create a copy of an item. You can then use the Move method to move the copied item to a new location.

The example on the following page returns the first item in the Product Ideas folder with the value Boating in the Product Category field. It then uses the Copy method to create a copy of the item returned from the Product Ideas folder. If the user selects Yes in the message box, the Move method copies the item from the Product Ideas folder to the Drafts folder. If you want to move rather than copy the item, use the Delete method and place a MyItem.Delete statement after the MyItem.Copy statement.

Creating and displaying a custom post item

You can use the Display method of the PostItem object to display an item on the desktop. As discussed earlier, you use the Add method of the Items collection object to create a new custom Post item. The following example returns the Product Ideas folder and then creates a new custom PostItem object by using the Add method of the Items collection object. It then displays the item in the Product Idea form. If you click the Post button on the form, the item is posted in the Product Ideas folder.

Posting an item

You can use the Post method of the PostItem object to post an item in a folder. The following example sets the folder to the Product Ideas folder. It then creates a new item with the message class IPM.Post.Product Idea, which is added to the Product Ideas Items collection. In this procedure, the object returned to MyItem by the Add method has a base message class of IPM.Post so you can use the Post method. The Subject and Body properties of the MyItem object are set, and then the item is posted to the Product Ideas folder.

The MailItem Object

The MailItem object represents a message in a mail folder. This section also covers some of the methods and properties of the PostItem object. Properties of the PostItem object are similar to the properties of the MailItem object, so they are discussed together.

Import!ant   Open the MailItem object and PostItem object items in the VBScript! Samples folder to work directly with this code in Outlook.

MailItem Object Methods

This section covers the Send, Reply, and Close methods of the MailItem object.

If your code attempts to send a message programmatically, the Warning dialog box shown in Figure 11-9 will be displayed. See Chapter 13 for methods to eliminate the Warning dialog box.

Figure 11-9. This Warning dialog box appears when you attempt to send a message programatically.

Sending a message

You can use the Send method of the MailItem object to send a message to a recipient. The following example creates a Mail Message item, sets the Subject and message Body fields, and then sets the To field to your name. You can retrieve the ScriptText property of the FormDescription object for the item to set the Body property of the message. It then uses the Send method to send the item to the specified recipient.

Note   The Body property of the item only lets you set plain text as the message text. If you want to format the Body programmatically, use the HTMLBody property discussed on page 487.

Replying to a message

You can use the Reply method of a MailItem object to return a Reply item. The following example creates a Reply item based on the current item, and then returns the Reply item represented by the MyReply object. The Reply item is then displayed. To run this example, you must first put a CommandButton1 control on the Read page of a Mail Message form. Exit Design mode and send the item to your Inbox, and then open the item in the Inbox and click CommandButton1. The Reply item is displayed.

Closing an item

You can use the Close method of the MailItem object to close an item. When you close the item, you also close the item’s associated form. The following example closes the current item when the CloseAnItem button is clicked. Note that if the blnIsDirty script-level variable is True, then the user is prompted to save changes. If blnIsDirty is False, then the item is closed and changes are not saved. You could modify this procedure to automatically save changes to a dirty form. This example also illustrates how you can write event procedures in the code for your custom form to control how and when the form is saved.

You can use one of the arguments in the table on the following page with the Close method or use CONST declarations as shown in the preceding example.

Save Option Value
Save all changes without prompting 0
Discard all changes without prompting 1
Prompt to save or discard all changes 2

Note   Unlike previous versions of Outlook, Outlook 2000 and 2002 allow you to write VBA or Visual Basic code to respond to all the events that are raised in a Message item. For additional information, see Chapter 9 and Chapter 14.

MailItem and PostItem Objects Properties

This section covers the GetInspector, Body, HTMLBody, To, and SenderName properties of the MailItem and PostItem objects.

Using GetInspector to reference the form

You can use the GetInspector property of the MailItem object or the PostItem object to reference the form associated with an item. You can then reference the page on the form, and then the controls on the page. The following example uses the GetInspector property of the MailItem object to return the form associated with the item. It references the Message page on the form and then sets the Visible property of the TextBox1 control to False.

Before you run this example, do the following:

  1. If you don’t have a TextBox1 control on the form, click Design This Form from Forms on the Tools menu to switch to Design mode.
  2. Drag a TextBox control from the Control Toolbox to the form.
  3. Click Run This Form on the Form menu to switch to Run mode, and then click CommandButton1 to hide the TextBox1 control.

Setting the message text of an item

You can use the Body property of a MailItem object or a PostItem object to specify the text that appears in the Message control of a Mail Message. The following example creates a Reply item, enters text in the Message control of the Reply item, and then sends the form: