Tuesday, July 2, 2013

VBA: Get the contents of a search folder (Outlook 2013)

There's a different way of accessing search folders with VBA versus regular mail folders in Outlook. This seems to be poorly documented online so I thought I'd help out with that.

First, you will need to determine the display name of the Outlook store which contains your search folders.
Use this code to list your stores.

Sub FindYourStore()
    Dim colStores As Outlook.Stores
    Dim oStore As Outlook.store

    On Error Resume Next
    Set colStores = Application.Session.Stores
'You may use Session.Stores as shortcut
        For Each oStore In colStores
            Debug.Print oStore.DisplayName
End Sub

With the name of the Outlook store, you plug that into the next subroutine. In my case, I was using this routine to parse emails in this folder. This routine will list the subject lines of every email in the designated search folder.


Sub ListSubjectLinesOfEmailsInASearchFolder()
    Dim StoreName As String
    Dim FolderName As String
    StoreName = "myemail@mycorp.com"
    FolderName = "Pending Terminations"
    Dim colStores As Outlook.Stores
    Dim oStore As Outlook.store
    Dim oSearchFolders As Outlook.Folders
    Dim oFolder As Outlook.Folder
    Dim mail As Outlook.MailItem

    On Error Resume Next
    Set oFolder = Session.Stores.Item(StoreName).GetSearchFolders(FolderName)
        For Each mail In oFolder.Items
            Debug.Print mail.Subject
End Sub

I hope that helps someone else out there.