Automating Microsoft Outlook 98
Home ] Up ] Client Server ] Crittografia ] ERP ] SQL ] TCP-IP ] E-Commerce ] Query Manager ] [ Automating Microsoft Outlook 98 ] BarCode ] Asp ] Il Modello Relazionale ] Studies for a Virus ] Utilizzo e creazione ] Virus ] Metodi Ottimali di Progettazione Sul WEB ] Printing ] Printing ] Masterizzare ] Strumenti ] OOP ] Backup ] Applicativi in Licenza ] Sicurezza ] Idee e Spunti ]

 

 

 

  All Products  |   Support  |   Search  |   microsoft.com Guide  
  Home   |   Access   |   Excel   |   FrontPage   |   Outlook   |   PowerPoint   |   Word   |

August 21, 1998     Back to Microsoft Outlook Articles and Sample Apps

Automating Microsoft Outlook 98

By Mindy Martin

This article originally appeared in the conference proceedings for the Microsoft Office and VBA Solutions Conference and Exposition, held in London, England, July 12-15, 1998, and is reprinted with permission of Informant Communications Group, Inc. Please visit their Web site at Leaving www.microsoft.comhttp://www.informant.com/mod/index.asp.

Download the sample code discussed in this article.

What Can Outlook Do For Me?

Microsoft Outlook, a desktop information manager and 32-bit email client, is the newest addition to the Microsoft Office suite. Designed for optimal use as the email client to Exchange 5.5, Outlook is the replacement for both the Exchange client and Schedule+. In addition to email capabilities, Outlook has a number of personal management modules such as a calendar tool for setting appointments, contact management, task management, and a journal tracking system. By utilising Outlook functionality, you can add modules to your Office applications that can be used for collecting and submitting information, document tracking, item requests, purchase orders, and registration and notification.

Outlook Object Model

The first step towards integrating Outlook functionality into your applications is to understand the Outlook object model. Figure 1 displays a sample of the Outlook object model. At the top is the Application object, which represents Outlook as a whole. Below the Application object is the Namespace object, which represents the message store. The Namespace object contains Folders, which in turn contain Items. An item is a particular instance of Outlook data such as a mail message or a contact.

 


 

  Outlook 98 Object Model


 

 

Application.   The Application object represents the entire Outlook application and is the top object in the hierarchy. The Application object is also the only object that can be returned when Automating Outlook. The major purposes of the Application object are as follows:

  • Provides access to the other objects in the outlook object model through the Namespace and Folders objects.
  • Allows for direct creation of new items such as mail messages and contact entries by using the CreateItem method.
  • Provides access to the Outlook interface objects such as Explorer, Inspector, and the Office Assistant.

Namespace.   The Namespace object represents the messaging service provider or message store. Currently the only available message store in Outlook is MAPI, which allows access to all Outlook folders and items. Some of the features of the Namespace object include:

  • Provides methods for logging in and logging out.
  • Allows for direct access to folders and items using an ID.
  • Gives access to data sources owned by other users.

Folders.   All Outlook items are contained within folders. These folders are then grouped into a collection of folders called the Folders collection object. The Folders collection object represents a collection of all folders within Outlook. Although currently only MAPIFolder objects exist in this collection, eventually other folder types may exist.

MAPIFolder.   A MAPIFolder object represents a single Outlook folder such as Contacts or the Inbox. A MAPIFolder object can contain individual items such as messages or appointments, or it can contain other folders. Folders can be typed to contain only a default item such as only mail items or only appointment items.

Items.   Every folder has an Items collection object, which represents all Outlook objects within that folder. The Items collection can be broken down further into specific types of items such as mail messages, appointments, and tasks.

AddressLists and AddressEntries.   The AddressLists collection object represents all of the address books installed for a particular profile. Within each individual AddressList object is a collection of AddressEntries. This collection contains all of the entries in that particular book. Entries can be added, edited and removed programmatically.

Initializing an Outlook Session

To begin Automating Outlook, you must first set a reference to the Outlook type library. Within your project, bring up your references dialog box and select the Microsoft Outlook 8.5 Object Library option. If this is not visible, browse for the file, MSOUTL85.OLB, wherever Office 97 was installed.

After a reference has been set, create a new instance of the Outlook application class object. The Application object is the only object that can be referenced directly. If Outlook was not currently running, it will be started and minimized. If Outlook is already running, a new instance will not be created, but a reference to the current one is returned.

Once a reference is set to the Application object, you can then specify a namespace and logon to the system. Use the GetNamespace method of the Application object to establish a MAPI namespace and then call the Logon method of the Namespace object to officially logon to Outlook. The Logon method takes up to four optional arguments:

  • Profile: This is a string value that indicates what MAPI profile to use for logging on. Leave blank if using the currently logged on user, or set to an empty string ("") if you wish to use the default Outlook Profile.
  • Password: The password for the indicated profile. Leave blank if using the currently logged on user, or set to an empty string ("") if you wish to use the default Outlook Profile password.
  • ShowDialog: Set to True to display the Outlook Profile dialog box.
  • NewSession: Set to True to start a new session. Set to False to use the current session.

Bypassing the use of the Logon method when Outlook is not running forces the Outlook Profile dialog box to be displayed or the default profile to be used. If Outlook is already running and the Logon method is bypassed, the current profile and session is used. Figure 2 creates a new instance of Outlook, retrieves the MAPI namespace, and displays the Outlook Profile dialog box to the user.

 


 

 
    Function startOutlook()
    Dim ol As New Outlook.Application
    Dim ns As Outlook.NameSpace

    'Return a reference to the MAPI layer
    Set ns = ol.GetNamespace("MAPI")

    'Let the user logon to Outlook with the
    'Outlook Profile dialog box,
    'and then create a new session
    ns.Logon , , True, True
End Function


 

Figure 2: The StartOutlook function starts a new instance of Outlook.

Simulating an Outlook Open Event in Access

As opposed to other Office 97 applications, Outlook does not have any events associated with the Application object. All events in Outlook are centred on the Outlook form, which is used to display item data. However, you can simulate an application's Open and Quit events if you are automating Outlook from Access or Visual Basic by wrapping a class module around an instance of Outlook.

Logging off

Of course once you have finished Automating Outlook, you should clean up and logoff of the current session. In addition, you should release all memory from your object variables no longer needed. Figure 3 demonstrates the use of the Logoff method.

 


 

 
Function CleanUpOutlook()
    ‘This logs the current profile off of a session
    ns.Logoff

    ‘Release all memory
    Set ns = Nothing
    Set ol = Nothing
End Function


 

Figure 3: Logging off of an Outlook session.

Navigating Folders

In order to move around in Outlook, you will need to know how to navigate within folders. All Outlook data is organised into folders, which often contain specific information. For example, a folder can be designated to only hold mail messages or contact information. This section covers how to access folders, navigate within nested folders, and how to create new folders.

Accessing Default folders

When Outlook is first installed, a number of default folders are created in the Outlook message store, and each folder is designed for a specific purpose and to hold a particular item type. For example the Inbox is used to receive incoming email.

You can use the GetDefaultFolder method of the Namespace object to return one of these folders. Figure 4 lists the folder names and the associated constant that is used with the GetDefaultFolder method.

Default Folder Default Folder Constant
Deleted Items OlFolderDeletedItems
Outbox OlFolderOutbox
Sent Items OlFolderSentMail
Inbox OlFolderInbox
Calendar OlFolderCalendar
Contacts OlFolderContacts
Journal OlFolderJournal
Notes OlFolderNotes
Tasks OlFolderTasks

Figure 4: Default folders and the associated constant.

Figure 5 demonstrates the use of the GetDefaultFolder method to retrieve the Inbox folder for the currently logged on user. After a MAPI message store has been returned, the GetDefaultFolder method is used to set a reference to the Inbox folder. Finally the folder is displayed in a new Outlook Explorer window. Even if Outlook is already running, a new window will be opened.

 


 

 
Sub GetDefaultInbox()
    Dim ol As New Outlook.Application
    Dim ns As Outlook.NameSpace
    Dim fdInbox As Outlook.MAPIFolder

    Set ns = ol.GetNamespace("MAPI")

    'Reference the default Inbox folder
    Set fdInbox = ns.GetDefaultFolder(olFolderInbox)

    'Display the Inbox in a new Explorer window
    fdInbox.Display
End Sub


 

Figure 5: Using the GetDefaultFolder method to retrieve the Inbox.

Returning A Delegate’s Folder

One of the more powerful features of Outlook allows you to access another user’s folders and items. To accomplish this, the user who is sharing a folder, the delegate, must first explicitly delegate access to the folder. Once this is done, you can use the GetSharedDefaultFolder method to return one of the delegate’s default folders.

In Figure 6, a new recipient is created for the name of the user passed into the procedure and resolved. If the person does exist in the network, return the default Calendar using the GetSharedDefaultFolder method, and display the folder in a new Outlook Explorer window. If the user doesn’t exist, alert the user to select a different person.

 


 

 
Sub GetSharedFolder(strRecip As String)
    Dim ol As New Outlook.Application
    Dim ns As Outlook.NameSpace
    Dim del As Outlook.Recipient
    Dim dfdCalendar As Outlook.MAPIFolder

    Set ns = ol.GetNamespace("MAPI")

    'Create a new recipient object and resolve it
    Set del = ns.CreateRecipient(strRecip)
    del.Resolve

    'If this user exists on the Exchange server..
    If del.Resolved Then
        'Get the shared calendar folder
        Set dfdCalendar = ns.GetSharedDefaultFolder _
            (del, olFolderCalendar)
        'Display it in a new Outlook Explorer window
        dfdCalendar.Display
    Else
        MsgBox "Unable to locate " & strRecip & ". _
 		Try another name.", vbInformation
    End If 
End Sub


 

Figure 6: Returning a delegate's default Calendar folder and displaying it.

Exploring Subfolders

Because you have the ability to create custom folders within Outlook, you may find it necessary to access a folder other than one of the default folders. For example, you may want to find a nested folder within the Inbox, or you may want to create a subfolder of an Exchange Public Folder. You can retrieve a nested folder by using a combination of the Folders property to return a collection of folders and by using the Folders(x) syntax to refer to the folder by name or index number. After locating the folder, use the Parent property to determine the container folder.

Figure 7 demonstrates how to loop through all of the nested folders of a Personal Folder to locate a particular folder. First a reference is set to return all of the folders contained within a Personal Folder called Development. Next a For Each loop is used to explore each of the nested folders looking for one named Acme. When the folder is found, the For Each loop is exited and the reference to the folder is maintained. To make sure the reference is good, the Parent property is used to display the name of the parent folder.

 


 

 
Sub ExploreFolders()
    Dim ol As New Outlook.Application
    Dim ns As Outlook.NameSpace
    Dim fds As Outlook.Folders
    Dim fd As Outlook.MAPIFolder

    Set ns = ol.GetNamespace("MAPI")
    'Set a reference to all folders within
    'a personal folder called development
    Set fds = ns.Folders("Development").Folders

    'Loop through all of the folders looking
    'for one named Acme.
    For Each fd In fds
        If fd.Name = "Acme" Then
            Exit For
        End If
    Next

    'Display the name of the parent folder
    MsgBox fd.Parent
End Sub


 

Figure 7: Locating a nested folder.

Adding Folders

To create a new folder in Outlook, use the Add method of the Folders collection object and pass the name of the new folder as a string argument. You can also indicate the type of items the folder will hold such as mail messages or contact items. If you do not supply this argument, the folder takes on the type of its parent folder. For example, if you create a new folder under the Inbox folder, the new folder defaults to hold mail messages.

In Figure 8, a reference is first set to the default Contact folder. Next the Folders property is used to return the Folders collection. Finally the Add method can then be called to create a new folder. The name is passes as an argument, but because the type is not indicated the folder will inherit the properties of the parent Contact folder.

 


 

 
Sub CreateNewFolder()
    Dim ol As New Outlook.Application
    Dim ns As Outlook.NameSpace
    Dim fdsConts As Outlook.MAPIFolder

    Set ns = ol.GetNamespace("MAPI")

    'Reference the default Contacts folder
    Set fdsConts = ns.GetDefaultFolder(olFolderContacts)

    'Add a new folder to the contacts folder collection
    'By not specifying the type, the folder will hold
    'Contact items.
    fdsDContacts.Folders.Add ("Acme Contacts")
End Sub


 

Figure 8: Create a new folder under the default Contact folder.

Working with Outlook Items

Within a folder is a collection of Items, which represent Outlook data. An Item can be one of a number of different types that represent the different functions of Outlook such as mail items, contacts, and appointments. Outlook items are actually instances of a message class. Outlook Items that can be created programmatically are listed and described in Figure 9.

 


 

 
Outlook Item Description
AppoinmentItem An appointment in a Calendar folder, which can be a meeting, one-time appointment, or recurring appointment or meeting.
ContactItem A contact in a Contacts folder.
JournalItem A journal entry in a Journal folder.
MailItem A mail message in a mail folder such as the Inbox.
NoteItem Post-it type note in a Notes folder.
PostItem Posting in a public folder that others may browse. Post items are not sent to anyone.
TaskItem A task in a Tasks folder. The task can be assigned, delegated, or self-imposed.


 

 

Figure 9: Outlook Items that can be created programmatically.

Creating Items

The easiest way to create a new item is to use the CreateItem method of the Application object. The CreateItem method creates a new standard Outlook item of the specified type and returns a reference to it. This method allows you to bypass navigating the object model to get to the methods of the Item object in order to create a new item. In Figure 10, a new Task item is created with the CreateItem method of the Application object. After creating the task, a few properties are set, and the item is saved.

 


 

 
Sub CreateTaskItem()
    Dim ol As New Outlook.Application
    Dim ns As Outlook.NameSpace
    Dim itmTask As Outlook.TaskItem

    Set ns = ol.GetNamespace("MAPI")

    ‘Create a new Task item    
    Set itmTask = ol.CreateItem(olTaskItem)

    ‘Set some properties of the Task item
    With itmTask
        .Subject = "Write article"
        .DueDate = "8/22/97"
        .Importance = olImportanceHigh
        .Save
    End With
End Sub


 

Figure 10: Creating a new Task item with the CreateItem method.

If you will be creating an item that is based on a customized Outlook form (a standard form that has been altered in Outlook), you can not use the CreateItem method. To create a new item based on a custom form, use the Add method of the Items collection object and pass the message class name of the custom form. Figure 11 demonstrates how to create a new item based on a custom form.

 


 

 
Sub CreateCustomTaskItem()
    Dim ol As New Outlook.Application
    Dim ns As Outlook.NameSpace
    Dim fdTasks As Outlook.MAPIFolder
    Dim fdAcme As Outlook.MAPIFolder
    Dim itmTask As Outlook.TaskItem

    Set ns = ol.GetNamespace("MAPI")

    'Reference the appropriate folders
    Set fdTasks = ns.GetDefaultFolder(olFolderTasks)
    Set fdAcme = fdTasks.Folders("Acme Project")

    'Create a new custom item and set some properties
    Set itmTask = fdAcme.Items.Add("IPM.Task.Acme Task")
    With itmTask
        .Subject = "Call Accounting"
        .DueDate = "12/1/97"
        .Importance = olImportanceLow
        .Save
    End With
End Sub


 

Figure 11: Creating a custom item using the Add method.

The Add method can also be used to create one of the standard items. By omitting the argument, an item of the default item type of the folder will be created. The following example creates a new custom Contact:

 


 

 
Set ol = Application.GetnameSpace("MAPI")
Set fdContacts = ol.GetDefaultFolder(olFolderContacts)

Set newContact = fdContacts.Items.Add 


 

Example: Sending Mail Messages

Probably the most common item you will work with is the mail message. The mail message item represents an email message. Aside from the common properties and methods including Subject, Body, To, CC, and Send, you will need to be able to work with two other objects nested within the item. These objects are the Recipients collection object, which represents all recipients of the email (To and CC alike), and the Attachments collection object, which represents any attachments to the email. Figure 12 demonstrates the creation of an email message with recipients and an attachment.

To indicate a recipient, use the Add method of the Recipients collection and pass the name or address of the user. To make certain that the person can be reached via email, use the Resolve method and the Resolved property.

To include an attachment to an email (or any item), use the Add method of the Attachments collection and pass the location of the file to be attached, and the way the file should be attached such as by reference or embedded. You can also specify a different display name for the item with the DisplayName property of the Attachment object.

 


 

 
Sub NewMailMessage()
    Dim ol As New Outlook.Application
    Dim ns As Outlook.NameSpace
    Dim newMail As Outlook.MailItem

    'Return a reference to the MAPI layer
    Set ns = ol.GetNamespace("MAPI")

    'Create a new mail message item
    Set newMail = ol.CreateItem(olMailItem)
    With newMail
        'Add the subject of the mail message
        .Subject = "Training Information for October 1997"
        'Create some body text
        .Body = "Here is the training information you requested:" & vbCrLf

        'Add a recipient and test to make sure that the
        'address is valid using the Resolve method
        With .Recipients.Add("mindym@imginc.com")
            .Type = olTo
            If Not .Resolve Then
                MsgBox "Unable to resolve address.", vbInformation
                Exit Sub
            End If
        End With

        'Attach a file as a link with an icon
        With .Attachments.Add _
            ("\\Training\training.xls", olByReference)
            .DisplayName = "Training info"
        End With

        'Send the mail message
        .Send
    End With

    'Release memory
    Set ol = Nothing
    Set ns = Nothing
    Set newMail = Nothing
End Sub


 

Figure 12: Creates a new mail message, attaches a file, and sends it.

Adding Hyperlinks

To bring the Internet and Intranet into your email, you can include Hyperlinks with your items. Hyperlinks may only be added within the Body of an item, but can be included in any Outlook item. Some of the more common protocols that can be used in Outlook are listed in Figure 13.

 


 

 
Protocol Description
File:// Used to open files on a local server.
FTP:// File Transfer Protocol(FTP) is used to transfer files over the Internet.
HTTP:// Hypertext Transfer Protocol(HTTP) is used to display web pages.
Mailto:// Used with an email address. Creates a new mail message to a particular person by clicking the hyperlink.
News:// Opens an Internet newsgroup. Recipient must be attached to a NNTP server.
Outlook:// Used to open an Outlook folder or item.


 

 

Figure 13: Common protocols used in hyperlinks in Outlook.

If any part of the hyperlink contains spaces, you must enclose the entire address in angled brackets. Figure 14 demonstrates the alternate use of a hyperlink to a file as opposed to attaching the file. Notice that the entire hyperlink is enclosed in angled brackets.

 


 

 
Sub useHyperlinks()
    Dim ol As New Outlook.Application
    Dim ns As Outlook.NameSpace
    Dim newMail As Outlook.MailItem

    Set ns = ol.GetNamespace("MAPI")

    'Create a new mail message item
    Set newMail = ol.CreateItem(olMailItem)
    With newMail
        .Subject = "Trainer Information for October 1997"

        'Create some body text with a hyperlink
        .Body = "Here is the training information you requested:" _
            & vbCrLf & "<file://training/trainer info.xls>"

        With .Recipients.Add("mindym@imginc.com")
            .Type = olTo
            If Not .Resolve Then
                MsgBox "Unable to resolve address.", vbInformation
                Exit Sub
            End If
        End With

        'Send the mail message
        .Send
    End With

    'Release memory
    Set ol = Nothing
    Set ns = Nothing
    Set newMail = Nothing
End Sub


 

Figure 14: Using hyperlinks in a Mail Message item.

Example: Scheduling Meetings

Another common interaction with Outlook is to schedule meetings. Some of the more common properties and methods include MeetingStatus, Start, End, Location, and Send. In addition, if you need to determine if a person is available or not, add the names of the attendees to the Recipients collection. You can then use the FreeBusy method to determine if the recipient is free or busy for a particular time slot.

Figure 15 demonstrates how to schedule a meeting. Start by creating an Appointment item, and then set the MeetingStatus property to olMeeting to turn the appointment into a meeting request. Next some properties are set such as where the meeting will be held, and the required attendees are indicated. You could also use the Recipients collection at this point and include the FreeBusy method. Finally a reminder is created and the invitations are sent out.

 


 

 
Sub ScheduleMeeting()
    Dim ol As New Outlook.Application
    Dim ns As Outlook.NameSpace
    Dim appt As Outlook.AppointmentItem

    'Return a reference to the MAPI layer
    Set ns = ol.GetNamespace("MAPI")

    'Create a new mail message item
    Set appt = ol.CreateItem(olAppointmentItem)
    With appt
        'By changing the meeting status to meeting, you create a
        'meeting invitation. You do not need to set this if
        'it is only an appointment
        .MeetingStatus = olMeeting
        'set the importance level to high
        .Importance = olImportanceHigh

        'Create a subject and add body text
        'Notice the hyperlink
        .Subject = "Acme Client Potential"
        .Body = "Let's get together to discuss the possibility of Acme " & _
            "becoming a client. Check out their website in the meantime:" _
            & vbCrLf & "http://www.acme.com"

        'Set the start and end time of the meeting and the location
        .Start = "10:00 AM 10/9/97"
        .End = "11:00 AM 10/9/97"
        .Location = "Meeting Room 1"

        'Invite the required attendees
        'These names will also be placed in the To field by default
        .RequiredAttendees = "RichardK; StefanieK"

        'Turn the reminder on and set it for 30 minutes prior
        .ReminderSet = True
        .ReminderMinutesBeforeStart = 30

        'Send the meeting request out
        .Send
    End With

    'Release memory
    Set ol = Nothing
    Set ns = Nothing
    Set appt = Nothing
End Sub


 

Figure 15: Schedules a meeting.

Finding Items

To find a particular item, use the Find method. The Find method applies a filter to the Items collection object of a folder and returns the first item that matches the filter. After the Find method runs, FindNext returns the next item in the collection that matches the filter. FindNext starts from the current position in the collection. The Find method uses a filter expression that evaluates to True or False and can contain one or more clauses joined by the logical operators And, Not, and Or. Property names can be used and should be included in square brackets. Variables and constants are not allowed.

Figure 16 demonstrates how to locate an item using the Find method. First a reference is set to the default Contacts folder, and then one is set to return the Items collection contained within the folder. Next a string variable is filled with the criteria to be used. Notice how the Contact property is in square brackets and the value must be enclosed within additional quotes. Finally the argument is passed to the Find method. If the item is not found, a message box is displayed; if it is found, the resulting Contact is displayed.

 


 

 
Sub FindAnItem()
    Dim ol As New Outlook.Application
    Dim ns As Outlook.NameSpace
    Dim fdContacts As Outlook.MAPIFolder
    Dim itmsContacts As Outlook.Items
    Dim itm As Object
    Dim criteria As String

    Set ns = ol.GetNamespace("MAPI")

    'Reference the deafult Contacts folder and then
    'return the Items collection of the folder
    Set fdContacts = ns.GetDefaultFolder(olFolderContacts)
    Set itmsContacts = fdContacts.Items

    'Establish the criteria and locate the Contact
    criteria = "[LastName] = 'Martin'"
    Set itm = itmsContacts.Find(criteria)

   'Determine if the item was found
    If itm Is Nothing Then
        MsgBox "Unable to locate the item."
    Else
        'Display the Contact
        itm.Display
    End If
End Sub


 

Figure 16: Locating an item using the Find method.

If you will be locating a subset of items in a folder, use the Restrict method. The Restrict method also applies a filter to a folder, but this method returns a new collection containing all items that match the filter. The Restrict method has slightly slower performance that the Find / FindNext methods, but it is handy in the sense that it returns a collection rather than a single item. Restrict also uses a filter.

Figure 17 demonstrates the use of the Restrict method. First a reference is made to the default Contact folder and then to all items in the folder. Next the criteria is set to locate all items with a category value of Holiday Cards. The argument is then passed to the Restrict method, which creates a new collection of items with that criterion. Finally a For Each loop displays each item.

 


 

 
Sub RetrictHolidayCards()
    Dim ol As New Outlook.Application
    Dim ns As Outlook.NameSpace
    Dim fdContacts As Outlook.MAPIFolder
    Dim itmsContacts As Outlook.Items
    Dim holidayCards As Outlook.Items
    Dim itm As Object
    Dim criteria As String

    Set ns = ol.GetNamespace("MAPI")
    'Reference the deafult Contacts folder and then
    'return the Items collection of the folder
    Set fdContacts = ns.GetDefaultFolder(olFolderContacts)
    Set itmsContacts = fdContacts.Items

    'Establish the criteria and locate all Contacts
    'with a category value of Holiday Cards
    criteria = "[Categories] = 'Holiday Cards'"
    Set holidayCards = itmsContacts.Restrict(criteria)

    For Each itm In holidayCards
        itm.Display
    Next
End Sub


 

Figure 17: Using the Restrict method to return a collection of Contacts.

The Restrict method can not be used with certain properties such as Saved and Unread. For a complete list, see Visual Basic for Outlook help file.

Retrieving Item Information

In addition to creating new items, you can also retrieve items and their properties to another application. For example, you can return all scheduling information to Excel for analysis or display message information in Access form.

To retrieve Outlook data, locate the folder that contains the information you require. Next use a For Each loop to loop through the items in the folder or use the Find method to find a particular item. Finally, use the properties of the individual item classes to acquire the necessary data.

Figure 18 uses a form in Access to display properties of unread messages. The Load event of the form begins a new instance of Outlook for the currently logged on user and places the subjects of all unread messages into a list box. Whenever a new subject is selected in the list box, various properties of the message are displayed in a number of textboxes.

 


 

 
Private ol As New Outlook.Application
Private ns As Outlook.NameSpace
Private itms As Outlook.Items

Private Sub Form_Load()
    Dim fd As Outlook.MAPIFolder
    Dim itm As Object

    'Get to the current session of Outlook
    Set ns = ol.GetNamespace("MAPI")
    'Retrieve a collection of mail messages in the inbox
    Set itms = ns.GetDefaultFolder(olFolderInbox).Items

    'Loop through the items and display the subjects of the unread
    'messages in a list box on a form
    For Each itm In itms
        If itm.UnRead = True Then
            lstSubjects.RowSource = lstSubjects.RowSource _
                & itm.Subject & ";"
        End If
    Next
End Sub

Private Sub lstSubjects_AfterUpdate()
    Dim itm As Object
    Dim criteria As String

    'Find the mail item with the subject currently selected
    'in a list box called lstSubjects
    criteria = "[subject] = '" & lstSubjects.Value & "'"
    Set itm = itms.Find(criteria)

    'Place some item information into text boxes
    txtFrom = itm.SenderName
    txtRecieved = itm.ReceivedTime
    txtBody = itm.Body
End Sub


 

Figure 18: Returning Outlook data to Access form controls.

Automating the Address Book

New in Microsoft Outlook 98 is the ability to programmatically access the address book for a particular profile. The approach to this is rather straightforward. Begin by returning a Namespace object. Next call the AddressLists property and pass a book name or index value. Once the particular address book has been returned, you can then use the AddressEntries property to return the entire contents of the book. This allows you to then add entries, edit entries, delete them, or simply read the list. Figure 19 demonstrates how to return the Personal Address Book, scroll though all of the entries, and fill an array with some of the properties of individual entries.

 


 

 
Sub RetrievePAB()
    Dim aPAB() As Variant
    Dim adl As Outlook.AddressList
    Dim e As Outlook.AddressEntry
    Dim i As Integer

    ReDim aPAB(100, 2)

    Set nsMAPI = ol.GetNamespace("MAPI")
    'Return the personal address book
    Set adl = nsMAPI.AddressLists("Personal Address Book")

    'Loop through all entries in the PAB
    ' and fill an array with some properties
    For Each e In adl.AddressEntries
        'Display name in address book
        aPAB(i, 0) = e.Name
        'Actual email address
        aPAB(i, 1) = e.Address
        'Type of address ie. internet, CCMail, etc.
        aPAB(i, 2) = e.Type
        i = i + 1
    Next
    ReDim aPAB(i - 1, 2)
End Sub


 

Figure 19: Reading the contents of a personal address book.

Summary

Microsoft Outlook 98 is a powerful email and personal management tool on its own, but when the abilities of Outlook are incorporated with other Office 97 applications, the possibilities are endless. Regardless if your application requires email capabilities, scheduling tools, or a contact management system, the Outlook object model can be automated to fulfil each of these needs and more. One object model, unlimited possibilities.

Mindy Martin is an independent consultant, trainer, and author based in Chicago, IL. Mindy is a Microsoft Certified Solution Developer and Microsoft Certified Trainer, and she specializes in everything VBA. Her primary focus is the integration of Microsoft Office into everything from the desktop environment to the Internet, but also finds enjoyment in the creation of collaborative applications with Outlook and Exchange. She is a contributing author to a number of development publications including Microsoft Office and Visual Basic for Applications Developer and VB/Access/Office Advisor and is currently working on a book on Excel for Sybex. She is a regular speaker at conferences worldwide including Tech*Ed, Informant, and Advisor DevCons.

Leaving www.microsoft.com This image means that the link points to servers that are not under Microsoft's control. Please read our official statement regarding other servers.

Top
 


 

 
 

Tell us about this article

-Very worth reading
-Worth reading
-Not worth reading
-Too detailed
-Just right
-Not detailed enough
-Too technical
-Just right
-Not technical enough




 

 
  Write us at MSOffDev@microsoft.com.  
  © 1998 Microsoft Corporation. All rights reserved. Legal Notices.
Last Updated: June 26, 1998
 
  Best experienced with
Microsoft Internet Explorer
Click here to start.