Share via


Working with Outlook Folders and Items

This content is no longer actively maintained. It is provided as is, for anyone who may still be using these technologies, with no warranties or claims of accuracy with regard to the most recent product version or service release.

You can think of the NameSpace object as the gateway to all existing Microsoft® Outlook® folders. By default, Outlook creates two top-level folders representing all public folders and all mailbox folders. Mailbox folders contain all Outlook built-in and custom folders. Each folder is a MAPIFolder object. MAPIFolder objects can contain subfolders (which are also MAPIFolder objects), as well as individual Outlook item objects, such as MailItem objects, ContactItem objects, JournalItem objects, and so on.

Note   In Outlook, an item is the object that holds information (similar to files in other applications). Items include mail messages, appointments, contacts, tasks, journal entries, and notes.

When you have created a NameSpace object variable, you can access the top-level folder for any built-in Outlook item by using the NameSpace object's GetDefaultFolder method. For example, the following code sample returns a reference to the ContactItems folder:

Dim fldContacts As Outlook.MAPIFolder
Set fldContacts = gnspNameSpace.GetDefaultFolder(olFolderContacts)

You can also return a reference to any folder by using the name of the folder. For example, the following procedure returns a reference to the folder in the current user's mailbox whose name is specified in the strFolderName argument:

Function GetFolderByName(strFolderName As String) As Outlook.MAPIFolder
   ' This procedure illustrates how to return a MAPIFolder
   ' object representing any folder in the mailbox folders
   ' collection whose name is specified by the strFolderName
   ' argument.
   Dim fldMain As Outlook.MAPIFolder
   
   On Error Resume Next
   
   ' Use the InitializeOutlook procedure to initialize global
   ' Application and NameSpace object variables, if necessary.
   If golApp Is Nothing Then
      If InitializeOutlook = False Then
         MsgBox "Unable to initialize Outlook Application " _
            & "or NameSpace object variables!"
         Exit Function
      End If
   End If
   
   Set fldMain = gnspNameSpace.Folders(GetMailboxName()).Folders(strFolderName)
   If Err = 0 Then
      Set GetFolderByName = fldMain
   Else
      ' Note: The most likely cause of an error here is that
      ' the folder specified in strFolderName could not be found.
      Set GetFolderByName = Nothing
   End If
End Function

The NameSpace object has at least two top-level folders representing all public folders and the user's mailbox. The preceding procedure uses the GetMailboxName procedure to return the name of the mailbox folder.

When you return a reference to a folder in the user's mailbox, that folder might contain additional folders, individual Outlook items, or both.

Sub GetFolderInfo(fldFolder As Outlook.MAPIFolder)
   ' This procedure prints to the Immediate window information
   ' about items contained in a folder.
   Dim objItem            As Object
   Dim dteCreateDate      As Date
   Dim strSubject         As String
   Dim strItemType        As String
   Dim intCounter         As Integer
   
   On Error Resume Next
   
   If fldFolder.Folders.Count > 0 Then
      For Each objItem In fldFolder.Folders
         Call GetFolderInfo(objItem)
      Next objItem
   End If
   Debug.Print "Folder '" & fldFolder.Name & "' (Contains " _
      & fldFolder.Items.Count & " items):"
   For Each objItem In fldFolder.Items
      intCounter = intCounter + 1
      With objItem
         dteCreateDate = .CreationTime
         strSubject = .Subject
         strItemType = TypeName(objItem)
      End With
      Debug.Print vbTab & "Item #" & intCounter & " - " _
         & strItemType & " - created on " _
         & Format(dteCreateDate, "mmmm dd, yyyy hh:mm am/pm") _
         & vbCrLf & vbTab & vbTab & "Subject: '" _
         & strSubject & "'" & vbCrLf
   Next objItem
End Sub

The GetFolderInfo procedure examines a folder for subfolders and calls itself recursively until there are no subfolders remaining. It then prints information about the items contained in the folder or subfolder to the Immediate window. Note that the objItem object variable is declared by using the Object data type so that the procedure can work with any Outlook item.

To work with a single item or subset of items in a folder, you use the Restrict method, which returns a collection of objects that match the criteria specified in the method's single argument. For example, the following procedure uses the Restrict method to create a collection of Outlook ContactItem objects that match the name supplied in the strLastName argument:

Function GetItemFromName(strLastName As String, _
                         Optional strFirstName As String = "", _
                         Optional strCompany As String = "") As Boolean
   ' This procedure returns an Outlook ContactItem that matches the
   ' criteria specified in the arguments passed to the procedure.
   Dim fldFolder            As Outlook.MAPIFolder
   Dim objItemsCollection   As Object
   Dim objItem              As Object
   Dim strCriteria          As String
   Dim objMatchingItem      As Object
   
   On Error GoTo GetItem_Err

   ' Use the InitializeOutlook procedure to initialize global
   ' Application and NameSpace object variables, if necessary.
   If golApp Is Nothing Then
      If InitializeOutlook = False Then
         MsgBox "Unable to initialize Outlook Application " _
            & "or NameSpace object variables!"
         Exit Function
      End If
   End If

   Set fldFolder = gnspNameSpace.GetDefaultFolder(olFolderContacts)

   If Len(strLastName) = 0 And Len(strFirstName) = 0 Then
      If Len(strCompany) > 0 Then
         strCriteria = "[Company] = '" & strCompany & "'"
      End If
   Else
      strCriteria = IIf(Len(strFirstName) = 0, _
         "[LastName] = '" & strLastName & "'", _
         "[LastName] = '" & strLastName & _
         "' AND [FirstName] = '" & strFirstName & "'")
   End If
   Set objItemsCollection = fldFolder.Items.Restrict(strCriteria)
   If objItemsCollection.Count > 0 Then
      If objItemsCollection.Count = 1 Then
         For Each objItem In objItemsCollection
            Set objMatchingItem = _
               gnspNameSpace.GetItemFromID(objItem.EntryId)
            objMatchingItem.Display
            GetItemFromName = True
            Exit Function
         Next objItem
      Else
         GetItemFromName = False
         Exit Function
      End If
   End If
   
   GetItemFromName = True

GetItem_End:
   Exit Function
GetItem_Err:
   GetItemFromName = False
   Resume GetItem_End
End Function

When you are using the Restrict method, you use Outlook field names within brackets to specify criteria for a search. You can join multiple criteria by using operators such as And, Or, and Not. For example, the following sample returns all the mail items sent in the last seven days that are unread and marked as highly important:

Dim fldMail       As Outlook.MAPIFolder
Dim itmItems      As Outlook.Items

strCriteria = "[SentOn] > '" & (Date - 7) _
   & "' And [UnRead] = True And [Importance] = High"

Set fldMail = gnspNameSpace.GetDefaultFolder(olFolderInbox)
Set itmItems = fldMail.Items.Restrict(strCriteria)

This line illustrates how to return all the Outlook ContactItem items that contain a value in the Business Address field:

Set objContacts = fldContacts.Items.Restrict("[BusinessAddress] <> '" & strZLS & "'")

The NorthwindContacts.dot sample file is a Microsoft® Word template that retrieves contacts from the Outlook Contacts folder and then displays the contacts in a UserForm. When the user selects a contact from the form, the contact name and address information is inserted in an address block in a letter.

Note   The NorthwindContacts.dot sample file also illustrates how to collect contact information from a database so that the user can insert name and address information into a letter.

See Also

Working with Microsoft Outlook Objects | Understanding the Application and NameSpace Objects | Understanding the Explorer and Inspector Objects | Understanding VBA in Outlook | Understanding Events in Outlook