Overview Using the Application Object Using the NameSpace Object Using the MAPIFolder Object Working with Outlook 2000 Items Programmatically Using the Explorer Object Using the In
Trang 1Contents
Overview 1
Working with Outlook 2000 Items
Programmatically 28
Lab A: Creating Address Labels by
Lab B: Adding an Outlook Bar Group
Review 73
Module 7: Working with the Microsoft Outlook 2000
Object Model
Trang 2to represent any real individual, company, product, or event, unless otherwise noted Complying with all applicable copyright laws is the responsibility of the user No part of this document may
be reproduced or transmitted in any form or by any means, electronic or mechanical, for any purpose, without the express written permission of Microsoft Corporation If, however, your only means of access is electronic, permission to print one copy is hereby granted
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property
1999 Microsoft Corporation All rights reserved
Microsoft, Active Desktop, Active Directory, ActiveX, BackOffice, Developer Studio, FrontPage, JScript, MSDN, MSN, NetMeeting, Outlook, PivotChart, PivotTable, PowerPoint, Visual Basic, Visual C++, Visual FoxPro, Visual InterDev, Visual J++, Visual SourceSafe, Visual Studio, Windows, Windows Media, and Windows NT are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A and/or other countries
The names of companies, products, people, characters, and/or data mentioned herein are fictitious and are in no way intended to represent any real individual, company, product, or event, unless otherwise noted
Other product and company names mentioned herein may be the trademarks of their respective owners
Project Advisor: Janet Wilson
Project Lead and Instructional Designer: Anne Bockman (Excell Data Corporation)
Instructional Designers: Josh Barnhill (Volt Technical) and Jo Berry (Exchange)
Lead Program Manager: Greg Bott
Program Managers: Colleena Carr and Chris Boar (Intl Vendor)
Graphic Artist: Andrea Heuston (Artitudes Layout and Design)
Editing Manager: Lynette Skinner
Editor: Jennifer Kerns (S&T Onsite)
Copy Editor: Shari G Smith (R & S Consulting)
Online Program Manager: Arlo Emerson (Aditi)
Production Support: Irene Barnett (Barnett Communications)
Manufacturing Manager: Bo Galford
Manufacturing Support: Mimi Dukes (S&T Onsite)
Development Services: Kimber Dodge
Lead Product Manager: Mary Larson
Group Product Manager: Robert Stewart
Trang 3Instructor Notes Module 7: Working with the Microsoft Outlook 2000 Object Model
This module provides students with a detailed understanding of the Microsoft®
Outlook® 2000 object model At the end of this module, students will be able to use Outlook development tools and the Outlook 2000 object model to develop components of collaborative applications
Materials and Preparation
This section provides you with the materials and preparation needed to teach this module
Materials
To teach this module, you need the following materials:
Microsoft PowerPoint® file 1593a_07.ppt
Module 7, “Working with the Microsoft Outlook 2000 Object Model”
Preparation
To prepare for this module, you should:
Read all the materials for this module
Read the instructor notes and margin notes for the module
Complete the labs
Rehearse the demo
Presentation:
90 Minutes
Labs:
60 Minutes
Trang 4Module Strategy
Use the following strategy to present this module:
Using the Application Object
Describe the properties and methods of the Application object and explain
how to use them in an application Explain how to handle the events of the
Application object
Using the NameSpace Object Describe the methods and properties of the NameSpace object and explain
how to use them in an application
Using the MAPIFolder Object Describe the methods and properties of the MAPIFolder object and explain
how to use them in an application
Working with Outlook 2000 Items Programmatically Explain how to reference items and limit the number of items returned by
using filtering Describe how to create new items by using the CreateItem method of the Application object and Add method of the Items collection,
and explain the difference between these two methods
Using the Explorer Object Explain how to use the properties, methods, and events of the Explorer
an OutlookBarPane object Explain how to add both a new group and a
new shortcut to the Outlook Bar
Trang 5Overview
Using the Application Object
Using the NameSpace Object
Using the MAPIFolder Object
Working with Outlook 2000 Items Programmatically
Using the Explorer Object
Using the Inspector Object
Working with the Outlook Bar
At the end of this module, you will be able to:
Incorporate support for Application object methods, events, and properties
in a collaborative application
Create new Microsoft® Outlook® 2000 items by using the Items collection
Incorporate methods and properties of the NameSpace object in a
Return an OutlookBarPane object and add a new group and a new shortcut
to the Outlook Bar in a collaborative application
In this module, you will learn
how to program the
methods, events, and
properties of the Outlook
object model to add
functionality to your
collaborative applications
Trang 6Using the Application Object
NameSpace
Folders (MAPIFolder)
Items (Item)
Explorers (Explorer) Inspectors (Inspector) Application
The Application object represents the entire Microsoft Outlook 2000
application and has several purposes:
As the root object, it allows access to other objects in the Outlook 2000 hierarchy
It allows direct access to a new Outlook 2000 item created by using the
CreateItem method, without having to traverse the object hierarchy
It allows access to the active interface objects (the Explorer and Inspector
objects)
If you develop with Outlook 2000 and previous versions of Outlook 2000, you may want to read the “What’s New for Microsoft Outlook 2000 Developers” article in Outlook 2000 Microsoft Visual Basic® for Applications Help
Slide Objective
To show the Application
object in relation to other
Outlook 2000 objects
Lead-in
Use the Application object
to access other objects in
the Outlook 2000 object
hierarchy, new
Outlook 2000 items, and
active interface objects
Note
Trang 7Referencing the Outlook 2000 Application Object
Using the Application Object from Within a Form
Using the Application Object from Within Visual Basic
Using the Application Object from Within Visual Basic for Applications Within Outlook 2000
Using the Application Object from Within a Folder Home Page
You can use automation to control Outlook 2000 from another application
Automation is a process that integrates two or more components in a way that appears seamless to the user Only one instance of the Outlook 2000 application executable file may be running at a given time The only object you can create
in the Outlook object model is the Application object This object resides at the
top of the object model
Using the Application Object from Within a Form
From within an Outlook 2000 form, you must use the Application property of the Item object to retrieve a reference to the Outlook 2000 application
Set objApp = Item.Application
Using the Application Object from Within Visual Basic
When using Visual Basic, you can use the CreateObject function to return a
reference to the Outlook 2000 application This is also true when using Visual Basic for Applications from within applications other than Outlook 2000 The
following example shows how to use the CreateObject function to return a reference to the Outlook 2000 Application object
Dim objApp As Outlook.Application Set objApp = CreateObject("Outlook.Application")
Slide Objective
To present an outline of this
topic
Lead-in
You can control functions of
Outlook 2000 from within
another application by using
automation
Trang 8Alternatively, you can set a reference to the Outlook object model and then
return a reference to the Outlook 2000 application by using the New keyword
This approach, as demonstrated in the following example, takes advantage of early binding
Dim objApp As Outlook.Application Set objApp = New Outlook.Application
Using the Application Object from Within Visual Basic for Applications Within Outlook 2000
The Application object is provided as an intrinsic object to your Visual Basic
for Applications project when working in Outlook 2000 You can refer to the
Outlook 2000 application simply by using the word Application
Using the Application Object from Within a Folder Home Page
In a folder home page, you can access the Outlook 2000 application by using a Microsoft Internet Explorer document object property, as shown in the
following example
Dim objApp Set objApp = Window.External.OutlookApplication
Trang 9Using Application Object Properties and Methods
Returning the Explorers and Inspectors Collections
Explorers property and Inspectors property
Returning the COMAddIns Collection
You can use properties and methods of the Application object to accomplish
certain programming tasks, such as returning the active window and returning
the Explorers and Inspectors collections
Returning the Explorers and Inspectors Collections
The Explorers collection contains a set of Explorer objects representing all Explorer objects An Explorer object need not be visible as a window to be included in the collection The Inspectors collection contains a set of Inspector objects representing all Inspectors objects An Inspector need not be visible as
a window to be included in the collection
Returning the Explorers Collection
The Explorers property returns the Explorers collection The following example shows how to retrieve the Explorers collection
Set objExplorers = objApp.Explorers
Returning the Inspectors Collection
Use the Inspectors property to return the Inspectors collection from the Application object The following example shows how to retrieve the Inspectors collection
Set objInspectors = objApp.Inspectors
Slide Objective
To identify methods and
properties of the
Application object that you
can use to accomplish
Trang 10Returning the COMAddIns Collection
Use the read-only COMAddIns property of the Application object to return the COMAddIns collection, which represents all the Component Object Model
(COM) add-ins currently loaded in Outlook 2000 Use the following syntax:
objApplication.COMAddIns, where objApplication is a required expression that
returns an Application object
The following Visual Basic example displays the number of COM add-ins currently connected
Dim objApp As New Outlook.Application
Private Sub cmdCount_Click()
MsgBox "There are " & objApp.COMAddIns.Count & " COM add-ins."
End Sub
If you use Visual Basic, Scripting Edition (VBScript), you do not declare an
Application object variable The following example shows how to perform the
same task by using VBScript
Sub cmdCount_Click()
MsgBox "There are " & Item.Application.COMAddIns.Count & " COM add-ins."
End Sub
Returning the Active Window
The ActiveWindow method returns the object that represents the topmost
Outlook 2000 window on the desktop The return type for this object can be
either an Explorer object or an Inspector object If no Explorer or Inspector
window is open, this method returns nothing Use this method to determine the state of that object The following code shows you how to use the
ActiveWindow method:
Set objWindow = objApp.ActiveWindow
If Not (objWindow Is Nothing) Then
If objWindow.Class = olExplorer Then strTop = "Explorer"
ElseIf objWindow.Class = olInspector Then strTop = "Inspector"
End If MsgBox "The topmost object is a(n) " & strTop & " object." End If
Trang 11Returning the NameSpace Object
You can use the GetNameSpace method of the Application object to return a NameSpace object of the type you specify Use the following syntax
objApplication.GetNameSpace(Type)
In this syntax, objApplication is a required expression that returns an
Application object and Type is the type of NameSpace to return
The only supported NameSpace is MAPI
The following VBScript example uses GetNameSpace to obtain the MAPI NameSpace object Because this example uses VBScript, you do not create the Application object
Set objNS = Item.Application.GetNameSpace("MAPI")
Note
Trang 12Handling Application Object Events
Application object events fire within Outlook 2000 These events occur either
because of a user action or a programmatic action Regardless of why the events occur, you can program your application to respond to the events For example, your application can respond when Outlook 2000 receives a new message or when the user exits the application
NewMail Event
The NewMail event fires when a new item is received in the Inbox for the current user This event does not pass any parameters There is not a one-to-one correspondence between the number of arriving messages and the number of times this event fires; the Inbox could receive many new messages but Outlook 2000 would fire this event only once per batch of messages delivered The following code shows you how to use the NewMail event:
Private Sub Application_NewMail() MsgBox "You have received new mail!"
End Sub
NewExplorer and NewInspector Events
The NewExplorer event fires when a new Explorer object is created The Explorer object represents the window in which the contents of a folder are displayed The NewInspector event fires when a new Inspector object is created The Inspector object represents the window in which an Outlook 2000
item is displayed The appropriate event fires when the corresponding object is created—either from the user interface (UI) or programmatically
Slide Objective
To list the Application
object events that fire within
Trang 13ItemSend Event
The ItemSend event fires whenever an attempt is made to send an item by using Outlook 2000 This event returns an object, which is the item the user or
application is trying to send, and a Boolean expression named Cancel (A
Boolean expression yields either a True or False value.) If you set Cancel to
True, Outlook 2000 stops the send action and leaves the inspector open for the user If you do cancel the send action, you should display an explanation in a message box, so that users know that they need to modify the item in some way
to send the item successfully
The following code checks to see whether a user added a subject and a category
to the message before the item is sent The code is written in Visual Basic for Applications within Outlook 2000
Private Sub Application_ItemSend(ByVal Item as Object, Cancel As Boolean)
If Item.Subject = "" Then
MsgBox "You must add a subject!"
ElseIf Item.Categories = "" Then
MsgBox "You must add a category!"
End Sub
The ItemSend event does not fire when a user posts an item to a folder
In this case, you should monitor the folder for the ItemAdd event
Quit Event
The Quit event is fired when Outlook 2000 begins to close By using this event, you can persist any settings or other information as well as destroy any objects that are left open by your application
Reminder Event
The Reminder event is fired just before a reminder is displayed This event passes one parameter, which is an object that corresponds to the item firing the reminder You cannot cancel this event, so you are notified only that a reminder
is going to appear The following example shows you how to use the Reminder event:
Private Sub Application_Reminder(ByVal Item As Object)
MsgBox "The following item " & Item.Subject & " has " & "fired a reminder." End Sub
Note
Trang 14Using the Reminder Event to Create a New Mail Item
The following Visual Basic example tests the item generating the reminder to
determine if it is a mail item If it is a mail item, the example uses the ReplyAll
method to create and display a new mail item The sample code must be placed
within a class module, and the Initialize_handler routine must be called before
the event procedure can be called
Dim WithEvents objApp As Outlook.Application Sub Initialize_handler()
Set objApp = CreateObject("Outlook.Application") End Sub
Private Sub objApp_Reminder(ByVal Item As Object) Dim objReplyItem As Outlook.MailItem
If TypeName(Item) = "MailItem" Then Set objReplyItem = Item.ReplyAll objReplyItem.Display
End If End Sub
Startup Event
The Startup event is fired after Outlook 2000 starts and loads any COM add-ins You can use this event to initialize Visual Basic for Applications programs that you create by using Outlook 2000
Trang 15Using the NameSpace Object
NameSpace
Folders (MAPIFolder)
Items (Item)
Explorers (Explorer) Inspectors (Inspector) Application
The NameSpace object is the primary way to use Outlook 2000 to access
objects that manipulate data stored in the MAPI storage system The
NameSpace object represents an abstract root object for the specified source (in
Outlook, MAPI is the datasource) The object provides methods for logging in and out, accessing storage objects directly by identifier (ID), accessing certain special default folders directly, and accessing data sources owned by other users
Slide Objective
To show the NameSpace
object in relation to other
Outlook 2000 objects
Lead-in
Use the NameSpace object
to access objects that
manipulate data stored in
Microsoft Exchange Server
Trang 16Using NameSpace Object Properties
Returning the Current User in the Outlook 2000 Session
Returning the Current User in the Outlook 2000 Session
The CurrentUser property returns the current user in the Outlook 2000 session Because the return value from this property is a Recipient object, you can
access more information about the user than just the user name However, the
name of the currently logged-on user (the Name property) is probably the used of the Recipient object
most-Slide Objective
To identify properties of the
NameSpace object that you
can use to accomplish
common tasks
Lead-in
You can use properties of
the NameSpace object to
return available address
lists, the current user in the
Outlook 2000 session, and a
Trang 17You can use the Name property and its corresponding Recipient object to
customize the UI for your forms based on the user who is logged on For example, you can automatically populate user name text boxes with the name of the currently logged-on user You can also programmatically hide or show fields based on the user The following example shows you both of these customizations:
Sub cmdHideFields_Click
Set objNS = Application.GetNameSpace("MAPI")
Set objCurrentUser = objNS.CurrentUser
Set objControls = Item.GetInspector.ModifiedFormPages("Status").Controls
Select Case objCurrentUser.Name
Case "Brad Sutton"
Returning a Collection of Available Folders
The Folders property returns a collection of all the available folders in the
current NameSpace You can then use the properties and methods of the
MAPIFolder object to perform specific actions on the folder The following
example shows you how to display the name of all the root folders in your folder hierarchy:
Sub cmdRootFolders_Click
Set objNS = Application.GetNameSpace("MAPI")
Set objFolders = objNS.Folders
Set objFolder = objFolders.GetFirst
Set objControls = Item.GetInspector.ModifiedFormPages("Root Folders").Controls For i = 1 To objFolders.Count
objControls("lstRootFolders").AddItem objFolders.Item(i).Name
Next
End Sub
Delivery Tip
The code for the following
procedure can be found at
\Studntcd\Demo\Module07\
RootFolders.oft
Trang 18Returning Available Address Lists
The AddressLists property returns the collection of the available address lists
for the current session Because Outlook 2000 can support multiple types of address lists, such as the personal address book, the Outlook 2000 address book, and the Exchange Server Global Address List (GAL), the types of address lists returned by this property can vary greatly
You should check the name or type of address list being returned before attempting to use the property In addition, Outlook 2000 allows your users to synchronize their address lists offline, so when designing your application, you should include support for an offline address list The following example shows you how to retrieve the address lists in Outlook 2000:
Sub cmdGetAddrLists_Click
Set objNS = Application.GetNameSpace("MAPI")
Set objALs = objNS.AddressLists
Set objControls = Item.GetInspector.ModifiedFormPages("Address Lists").Controls For Each objAddrList in objALs
objControls("lstAddrLists").AddItem objAddrList.Name
Next
End Sub
Delivery Tip
The code for the following
procedure can be found at
\Studntcd\Demo\Module07\
AddressLists.oft
Trang 19Using NameSpace Object Methods
Retrieving Standard Outlook 2000 Folders
Displaying the Pick Folder Dialog Box
Displaying the E-mail Address of a User
Viewing the Calendar of Another User
Accessing an Object by Using Its Unique ID
The methods of the NameSpace object provide a number of functions, such as
enabling you to do the following: create recipients; display the Outlook 2000
Select Folder dialog box; retrieve items, recipients, and folders by their unique
IDs; and allow users with proper permissions to access another user’s information
Retrieving Standard Outlook 2000 Folders
Outlook 2000 enables you to quickly retrieve the standard Outlook 2000 folders, such as the Inbox, Contact, and Task folders You do not have to search through the folder hierarchy to find them Instead, you can pass to the
GetDefaultFolder method the Outlook 2000 constant that corresponds to the
folder you want to retrieve VBScript in Outlook 2000 does not support constants, so you have to use the number that corresponds to the constant, as shown in the following example:
Sub cmdDisplayContacts_Click Set objNS = Application.GetNameSpace("MAPI") Set objContacts = oNS.GetDefaultFolder(10) ' Contacts objContacts.Display
End Sub
Slide Objective
To identify some common
functions that the
display the Pick Folder
dialog box, display the
e-mail addresses of a user,
view the calendar of another
user, and access an item by
using its unique ID
Trang 20Displaying the Pick Folder Dialog Box
You can enable users to select where to save their items or where the application will find the information it needs Outlook 2000 supports many different types of information stores, such as multiple personal stores, an Exchange Server private information store, and an Exchange Server public
folder store You can use the PickFolder method, which calls the same dialog
box that Outlook 2000 displays when its users decide where information should
be saved or which folder to query The PickFolder method displays a modal
dialog box, so the user will either have to pick a folder or cancel the dialog box
to continue The return value from this method is a MAPIFolder object that
corresponds to the folder picked by the user If the user cancels the dialog box,
the method returns Nothing
The following example shows how to use the PickFolder method and then
display the folder that the user picked
Sub cmdPickFolder_Click Set objNS = Application.GetNameSpace("MAPI") Set objFolder = objNS.PickFolder()
If objFolder Is Nothing Then MsgBox "You did not pick a folder"
Else objFolder.Display End If
End Sub
Displaying the E-mail Address of a User
The CreateRecipient method takes a string as its argument This string should
correspond to the user’s display name If a successful object is returned to you, you know that the recipient is in one of the address lists At that point, you can
pass the returned Recipient object to the GetSharedDefaultFolder method in
order to open that recipient’s shared personal folders The following code
shows you how to use the CurrentUser property to retrieve a Recipient object
It uses the returned object to display the X.500 formatted e-mail address of the user
Sub cmdDisplayAddress_Click Set objNS = Application.GetNameSpace("MAPI") Set objRecip = objNS.CurrentUser
MsgBox objRecip.Address End Sub
For access to the proxy addresses (such as SMTP), you must use
Collaboration Data Objects (CDO) to access the Fields collection
Delivery Tip
The code for the following
procedure can be found at
Trang 21Viewing the Calendar of Another User
Users of collaborative applications frequently request the ability to view the calendars of other users, within a single window Within Outlook 2000, you can
build this type of application by using the GetSharedDefaultFolder method This method takes a Recipient object and a constant that defines the default
folder, such as the Inbox, the Calendar, or the Tasks folder, that the user wants
to open This method is only used in the delegation scenario in which certain users have permissions on other users’ folders If the user of the application does not have permissions on the other user’s folders, Outlook 2000 returns an
error The following example demonstrates the GetSharedDefaultFolder
method
Sub cmdGetSharedFolder_Click Set objNS = Application.GetNameSpace("MAPI") Set objRecip = objNS.CreateRecipient("Adam Barr") '
' GetSharedDefaultFolder requires a resolved ' recipient
' objRecip.Resolve '
' olFolderTasks = 13 '
Set objTasks = objNS.GetSharedDefaultFolder(objRecip, 13) '
' Display the contents of the folder in a new Explorer '
objTasks.Display End Sub
Trang 22Accessing an Object by Using Its Unique ID
The EntryID property is a globally unique identifier that corresponds to the MAPI global identifier PR_ENTRYID, which is a property of the Outlook
object It returns the unique entry ID of the object and corresponds to the MAPI
property PR_ENTRYID If you pass the EntryID property to any of three methods—GetFolderFromID, GetRecipientFromID, and
GetItemFromID—the method will return the appropriate item These methods
are helpful when you know the item’s unique ID and need to access the item quickly, but do not have time to search through the Exchange Server
information store For example, the following code stores the EntryID and StoreID for the first folder in the default Tasks folder and then displays it This
could be used within MoveApp to access the Tasks subfolders of technicians Sub cmdGetFolder_Click
Set objNS = Application.GetNameSpace("MAPI")
' Get the default Tasks folder
Set objTasks = objNS.GetDefaultFolder(13)
' Get the first subfolder in the collection
Set objTasksSubFolder = objTasks.Folders(1)
' Store the Entry and Store IDs
strEntryID = objTasksSubFolder.EntryID
strStoreID = objTasksSubFolder.StoreID
' Use the IDs to display the folder
Set objFolder = objNS.GetFolderFromID(strEntryID, strStoreID)
Trang 23Using the MAPIFolder Object
NameSpace
Folders (MAPIFolder)
Items (Item)
Explorers (Explorer) Inspectors (Inspector) Application
The MAPIFolder object represents an Outlook 2000 folder A MAPIFolder object can contain other MAPIFolder objects, as well as Outlook 2000 items The Items collection of a MAPIFolder object contains the objects that
represent all the Outlook 2000 items in the specified folder (If a given folder
does not contain any Outlook 2000 items, the Count property for the Items
collection is 0 [zero].)
Slide Objective
To show the MAPIFolder
object in relation to other
Outlook 2000 objects
Lead-in
You can use the
MAPIFolder object in
conjunction with the Items
collection to navigate the
Outlook 2000 folder
hierarchy
Trang 24Navigating Nested Folders
Folders Object and Parent Property Example
Function Messages_Parent()
'Assume objMessages has already been defined.Set objMessages = objMsg.Parent
If objMessages Is Nothing Then
MsgBox "No Messages collection available." Exit Function
End If MsgBox "Messages collection parent class = " _
& objMessages.Parent.Class End Function
Function Messages_Parent()
'Assume objMessages has already been defined
Set objMessages = objMsg.Parent
If objMessages Is Nothing Then
MsgBox "No Messages collection available." Exit Function
End If MsgBox "Messages collection parent class = " _
& objMessages.Parent.Class End Function
You can navigate nested folders by using a combination of the Folders object, which returns a folder within a NameSpace or another folder, and the Parent
property, which returns the containing object
The Parent property represents the immediate parent of the object, rather than the logical parent For example, a folder contains a Messages collection, which
contains Message objects The Parent property for a message is the immediate parent, the Messages collection, rather than the logical parent, the Folder
object
Folders Object and Parent Property Example
To obtain a reference to the Folder object, you use the Parent property of the Messages collection, as shown in the following example:
Function Messages_Parent()
'Assume objMessages has already been defined
Set objMessages = objMsg.Parent
If objMessages Is Nothing Then
MsgBox "No Messages collection available."
You use a combination of
the Folders object and the
Parent property to navigate
nested folders
Trang 25Working with Folders Collection Events
Using the FolderAdd Event
Using the FolderChange Event
Using the FolderRemove Event
The Folders collection is a collection of MAPIFolder objects that represent all
the available Outlook 2000 folders in a specific subset at one level of the folder
tree By using the methods of the Folders collection object, you can perform
the standard functions you would expect on folders, such as adding, finding, and deleting folders in the collection Most folder actions have corresponding events such as FolderAdd, FolderChange, and FolderRemove
Using the FolderAdd Event
The FolderAdd event occurs when a folder is added to the specified Folders
collection This event is not available in VBScript Use the following syntax
Sub object_FolderAdd(Folder as MAPIFolder)
In this syntax, object is an expression that evaluates to a Folders collection
object and Folder is the MAPIFolder that was added to the collection
Slide Objective
To list the most commonly
used events of the Folders
collection object
Lead-in
Use the methods of the
Folders collection object to
perform standard folder
functions, such as adding,
sorting, finding, and deleting
folders in the collection
Trang 26The following example displays a new folder created in the user’s Inbox Dim objOlApp As New Outlook.Application
Public WithEvents objFolders As Outlook.Folders
Public Sub Initialize_handler()
Set objFolders = objOlApp.GetNameSpace("MAPI") _
Using the FolderChange Event
The FolderChange event occurs when a folder in the specified Folders
collection is changed This event is not available in VBScript Use the following syntax
Sub object_FolderChange(Folder as MAPIFolder)
In this syntax, object is an expression that evaluates to a Folders collection
object and Folder is the MAPIFolder that was changed
The following example prompts the user to remove a folder from the Deleted Items folder if the folder is empty The sample code must be placed in a class module, and the Initialize_handler routine must be called before the event procedure can be called by Outlook 2000
Dim objOlapp As New Outlook.Application
Dim WithEvents objFolders As Outlook.Folders
Sub Initialize_handler()
Set objNS = objApp.GetNameSpace("MAPI")
Set objFolders = objNS.GetDefaultFolder(olFolderDeletedItems).Folders
End Sub
Private Sub objFolders_FolderChange(ByVal Folder As Outlook.MAPIFolder)
If Folder.Items.Count = 0 Then
strPrompt = Folder.Name & " is empty Do you want to delete it?"
Folder.Delete
End Sub
Trang 27Using the FolderRemove Event
The FolderRemove event occurs when a folder is removed from the specified
Folders collection This event is not available in VBScript Use the following
Dim objOlapp As New Outlook.Application
Dim WithEvents objFolders As Outlook.Folders
Sub Initialize_handler()
Set objNS = objApp.GetNameSpace("MAPI")
Set objFolders = objNS.GetDefaultFolder(olFolderDeletedItems).Folders
Trang 28Working with MAPIFolder Object Methods
Using the GetExplorer Method
Using the CopyTo Method
Using the MoveTo Method
You can use some of the methods of the MAPIFolder object to return a
reference to the Explorer window of a folder or to copy or move a folder from one location to another
Using the GetExplorer Method
The GetExplorer method returns an initialized, inactive Explorer object with the current folder object as its initial folder Once the inactive Explorer object
is returned, you can use the Display method to display the Explorer
GetExplorer also takes an optional argument, which is the navigation type of the returned Explorer object This argument takes one of three constants
Outlook 2000 client with the Outlook Bar, a message panel, and a folder banner
folder list or Outlook Bar
most restrictive way, without any navigation capabilities at all, including no folder list and no drop-down folder list The user will not be able to switch
to any other folder besides the one in the Explorer
You must clear all references to Explorer objects—both active and
inactive—in your code, or Outlook will continue to run on the computer It is
good practice to set all Explorer objects that are not needed to Nothing in the
Item_Close event
Slide Objective
To list the commonly used
methods of the MAPIFolder
object
Lead-in
GetExplorer, CopyTo, and
MoveTo are three methods
of the MAPIFolder object
that you will use frequently
Trang 29The following code example opens three folders by using the three different
modes of the GetExplorer method
Sub cmdOpenFolders_Click Set objNS = Application.GetNameSpace("MAPI") Set objInbox = objNS.GetDefaultFolder(6) Set objCalendar = objNS.GetDefaultFolder(9) Set objContacts = objNS.GetDefaultFolder(10) Set objExplorerMode0 = objInbox.GetExplorer(0) objExplorerMode0.Display
Set objExplorerMode1 = objCalendar.GetExplorer(1) objExplorerMode1.Display
Set objExplorerMode2 = objContacts.GetExplorer(2) objExplorerMode2.Display
End Sub
Using the CopyTo Method
The CopyTo method copies the current folder in its entirety to the destination folder This method returns a MAPIFolder object that represents the new copy
Use the following syntax
objMAPIFolder.CopyTo(DestFldr)
In this syntax, objMAPIFolder represents an expression that returns a
MAPIFolder object (the current folder) and DestFldr represents a
MAPIFolder object (the destination folder for the copied folder)
The following VBScript example uses the CopyTo method to copy the current
folder (in this case, the default Contacts folder) to the default Inbox folder Set objNameSpace = Application.GetNameSpace("MAPI")
Set objInboxFolder = objNameSpace.GetDefaultFolder(6) Set objCurrentFolder = objNameSpace.GetDefaultFolder(10) Set objNewFolder = objCurrentFolder.CopyTo(objInboxFolder)
Using the MoveTo Method
The MoveTo method of the MAPIFolder object moves a folder to a
destination folder that you specify Use the following syntax
The following VBScript example adds a new folder to the default Contacts
folder, and then uses the MoveTo method to move it to the default Inbox folder
Set objNS = Application.GetNameSpace("MAPI") Set objFolder = objNS.GetDefaultFolder(10) Set objNewFolder = objFolder.Folders.Add("My Contacts") objNewFolder.MoveTo objNS.GetDefaultFolder(6)
Trang 30Working with MAPIFolder Object Properties
Using the DefaultItemType Property
Using the DefaultMessageClass Property
Using the Folders Property
This section describes the properties and shows how you can use them in your collaborative applications
Using the DefautItemType Property
The DefaultItemType property returns the Outlook 2000 default item type for
the folder, such as olContactItem (2), olTaskItem (3), and olMailItem (0) Even though a certain Outlook 2000 type might be the default item type for a folder,
it is possible to have other types of items in the folder The following code example block-checks the default item type for a folder and then displays this to the user
Slide Objective
To list the most commonly
used properties of the
MAPIFolder object
Lead-in
You will frequently use
these three properties of the
Trang 31Sub cmdDisplayDefaultItem_Click
Set objNS = Application.GetNameSpace("MAPI")
Set objInbox = objNS.GetDefaultFolder(6)
Using the DefaultMessageClass Property
The DefaultMessageClass property, which is read-only, returns a string that
contains the default message class set for the folder For most folders in your mailbox, this default is a standard message class such as IPM.Note or IPM.Contact However, for your application folders, this default can be any valid message class for your custom forms, such as IPM.Contact.Account info
or IPM.Task.Project Tracking The following example loops through all level folders in your mailbox and displays the default message class for each folder
top-Sub cmdDisplayMsgClass_Click
Set objNS = Application.GetNameSpace("MAPI")
strCurrentUser = objNS.CurrentUser.Name
Set objMAPIFolder = objNS.Folders("Mailbox - " & strCurrentUser)
Set objMAPIFolders = objMAPIFolder.Folders
For Each objFolder in objMAPIFolders
MsgBox "The default message class for " _
& objFolder.Name & " is: " & objFolder.DefaultMessageClass
Next
End Sub
Using the Folders Property
Because Outlook 2000 folders can have subfolders, the Folders property of the MAPIFolder object returns all the folders that the current folder contains
Trang 32Working with Outlook 2000 Items Programmatically
NameSpace
Folders (MAPIFolder)
Items (Item)
Explorers (Explorer) Inspectors (Inspector) Application
Outlook 2000 allows items to be scripted from within a form by using VBScript It is also possible to program Outlook 2000 items from Visual Basic
or Visual Basic for Applications by using the objects and properties provided
by the Outlook object model
Slide Objective
To show the Items
collection in relation to other
Outlook 2000 objects
Lead-in
You can work with
Outlook 2000 items
programmatically, both from
within an Outlook 2000 form
and from outside of a form
Trang 33Returning an Item from the Items Collection
Returning an Item by Using Its Subject Name
Returning an Item by Its Position within the Collection
Returning an Item by Its EntryID
Set objFolder = Item.Application.GetNameSpace("MAPI") _
GetDefaultFolder(6) ' 6 = olFolderInboxSet objItem = objFolder.Items("Need your advice")
Set objFolder = Item.Application.GetNameSpace("MAPI") _
GetDefaultFolder(6) ' 6 = olFolderInboxSet objItem = objFolder.Items("Need your advice")
Set objFolder = Item.Application.GetNameSpace("MAPI") _
GetDefaultFolder(6) ' 6 = olFolderInboxSet objItem = objFolder.Items(1)
Set objFolder = Item.Application.GetNameSpace("MAPI") _
GetDefaultFolder(6) ' 6 = olFolderInboxSet objItem = objFolder.Items(1)
The Items collection of a MAPIFolder object contains the objects that
represent all the Outlook 2000 items in the specified folder If a given folder
does not contain any Outlook 2000 items, the Count property for the Items
collection is 0 (zero)
To return the Items collection of a MAPIFolder object, use the Items property
To return a single AppointmentItem, ContactItem, JournalItem, MailItem, NoteItem, PostItem, or TaskItem object from its respective Items collection,
use Items(index), where index is the subject name or index number for the item
Returning an Item by Using Its Subject Name
The following example returns the first item with the subject “Need your advice” in oFolder
Set objFolder = Item.Application.GetNameSpace("MAPI") _ GetDefaultFolder(6) ' 6 = olFolderInbox
Set objItem = objFolder.Items("Need your advice")
Returning an Item by Its Position within the Collection
The following example returns the first item in oFolder By default, items in the collection are sorted by their Creation Date/Time field
Set objFolder = Item.Application.GetNameSpace("MAPI") _ GetDefaultFolder(6) ' 6 = olFolderInbox
Set objItem = objFolder.Items(1)
Slide Objective
To show how to use the
Items collection to return a
single item
Lead-in
Use the Items collection of
the MAPIFolder object to
return a collection of all of
the Outlook 2000 items in
the specified folder
Trang 34Returning an Item by Its EntryID
The following example shows how the cmdGetEntryID_Click subroutine saves the EntryID for the first item in the folder The second subroutine,
cmdDisplayMsg_Click uses this saved EntryID to retrieve the message directly Dim objNS
Dim strEntryID Sub cmdGetEntryID_Click() ' \Studntcd\Demo\Module07\EntryID.oft Dim objFolder
Set objNS = Item.Application.GetNameSpace("MAPI") Set objFolder = objNS.PickFolder()
' Save the EntryID of the first item in the folder strEntryID = objFolder.Items(1).EntryID
MsgBox strEntryID End Sub
Sub cmdDisplayMsg_Click() Dim objMessage
Set objMessage = objNS.GetItemFromID(strEntryID) objMessage.Display
End Sub
Delivery Tip
Code for the following
procedure can be found at
\StudntCd\Demo\Module07\
EntryID.oft
Trang 35Using the SetColumns and ResetColumns Methods
Using the SetColumns Method
Restrictions on the SetColumns Method
Using the ResetColumns Method
Sub cmdSetColumns_ClickSet objNS = Item.Application.GetNameSpace("MAPI")Set objInbox = objNS.GetDefaultFolder(6) ' InboxSet objItems = objInbox.Items
objItems.SetColumns "[Subject],[SenderName],[To]"End Sub
Sub cmdSetColumns_ClickSet objNS = Item.Application.GetNameSpace("MAPI")Set objInbox = objNS.GetDefaultFolder(6) ' InboxSet objItems = objInbox.Items
objItems.SetColumns "[Subject],[SenderName],[To]"End Sub
Outlook 2000 enables you to make your applications faster by using the
SetColumns method You can use this method to tell Outlook 2000 to limit the
properties to cache so that access to these properties is very fast You can use
the SetColumns method on custom properties, as well as intrinsic properties The SetColumns method is useful for iterating through the Items collection If
you do not use this method, Outlook 2000 must open each item to access the
property With the SetColumns method, Outlook 2000 only checks the
properties that you have cached The properties you do not include in the
parameters sent to SetColumns will return empty
Using the SetColumns Method
The following example shows you how to use the SetColumns method
Sub cmdSetColumns_Click ' \Studntcd\Demo\Module07\SetColumns.oft Set objNS = Application.GetNameSpace("MAPI") Set objInbox = objNS.GetDefaultFolder(6) Set objItems = objInbox.Items
objItems.SetColumns "[Subject],[SenderName],[To]"
End Sub
Slide Objective
To show a code sample that
uses the SetColumns
achieved when the number
of columns is small enough
that a lightweight item can
be used by Outlook 2000
and not the full item
Delivery Tip
Code for the following
procedure can be found at
\Studntcd\Demo\Module07\
SetColumns.oft
Trang 36Restrictions on the SetColumns Method
If the SetColumns method is used with a property that returns an object or with any of the following properties, an error will be returned The SetColumns method cannot be used with the following properties: Body, Categories, Children, Class, Companies, Contacts, DLName, EntryID, HTMLBody, MemberCount, RecurrenceState, ReplyRecipients, ResponseState, Saved, Sent, Submitted, and VotingOptions
Using the ResetColumns Method
The ResetColumns method resets the properties so that your application can access all the properties in the items You can then use the SetColumns method
again to cache a different set of properties
Trang 37Finding and Filtering Items in a Collection
Guidelines for Using the Find and Restrict Methods
Filters used with Find and Restrict are not
case-sensitive
Do not use the Find and Restrict methods to search for
a string within an Outlook field
Use the >, < , >=, and <= operators to perform a begins
with search
Contents of a variable can be used as part of the filter
You can use the Outlook object model to return information about all items in a folder Often, however, you want to search for a specific item or retrieve a subset of the items in the folder Consider the following examples
In MoveApp, the VBScript within the folder home page needs to test if the current user has a move item in the Employee Moves folder This search can
be done with a single line of code:
Set objMoveItem = EmployeeMoves.Find("[Employee Name] = '" & currentusername & "'")
To write a Visual Basic program to automatically schedule appointments in users’ calendars, you need to retrieve a user’s appointments for a given day
In this case, you would use the Restrict method to retrieve all appointments
that fall on a particular day
Slide Objective
To provide guidelines for
using the Find and Restrict
methods
Lead-in
The Find, FindNext, and
Restrict methods enable
you to search for individual
items and subsets of items
within collections
Trang 38Guidelines for Using the Find and Restrict Methods
While the Find and Restrict methods perform different functions, the syntax
for both is similar Follow these guidelines when you use these methods
The filters used with Find and Restrict are not case-sensitive
It is not possible to use these methods if you need to search for a string that
is contained within an Outlook 2000 field, commonly called a contains
operation If you need to perform a contains operation, you can iterate
through all of the items in the folder and use the Visual Basic InStr function
to determine whether your search string is contained within an Outlook 2000 field
To create a filter that performs a begins with operation, use the >, < , >=,
and <= operators For example, to search for all contacts whose last names begin with the text "Mc", use this filter: ""[LastName] >= ""Mc"" and [LastName] < ""Md"""
You can use the contents of a variable as part of the filter
Trang 39Creating New Items Based on Default Forms
CreateItem Method Examples
Using Visual Basic for Applications
Using VBScript
Dim objItem as Outlook.ContactItemSet objItem = Application.CreateItem(olContactItem)objItem.Display
Dim objItem as Outlook.ContactItemSet objItem = Application.CreateItem(olContactItem)objItem.Display
Dim objItemSet objItem = Application.CreateItem(2)objItem.Display
Dim objItemSet objItem = Application.CreateItem(2)objItem.Display
The CreateItem method creates one of seven default Outlook 2000 items and returns it The CreateItem method can only create default Outlook 2000 items The syntax for the CreateItem method is:
objApplication.CreateItem(ItemType)
CreateItem Method Examples
A new item can be created by using either Visual Basic for Applications or VBScript
Using Visual Basic for Applications
The following Visual Basic for Applications example creates a new contact item
Dim objItem as Outlook.ContactItem Set objItem = Application.CreateItem(olContactItem) objItem.Display
Using VBScript
The following example accomplishes the same task by using VBScript
Dim objItem Set objItem = Application.CreateItem(2) objItem.Display
Slide Objective
To show how to use the
CreateItem method to
create a new item that is
based on default forms
Lead-in
The CreateItem method
creates a new Outlook 2000
item that is based on a
default form and returns it