Working with VBA and non-default Outlook Folders

Last reviewed on October 17, 2013

This code sample uses a default Outlook folder:

Sub Whatever()
  Dim Ns As Outlook.NameSpace

  Set Ns = Application.GetNamespace("MAPI")

'use the default folder  
Set Items = Ns.GetDefaultFolder(olFolderCalendar).Items

'do whatever

End Sub

To use a folder at the same level as the Default folders (such as Calendar, Inbox etc), use this in place of Set Items = Ns.GetDefaultFolder(olFolderCalendar).Items, where SharedCal is the folder name:

Set Items = Session.GetDefaultFolder(olFolderCalendar).Parent._
     Folders("SharedCal").Items

When the folder is a subfolder under the default Calendar folder, use this instead:

Set Items = Session.GetDefaultFolder(olFolderCalendar)._
  Folders("SharedCal").Items

To use the currently selected folder, you'll need to use:

Set Items = Application.ActiveExplorer.CurrentFolder.Items

Use a folder in another pst or Mailbox

Folder pathsTo use a specific folder in another data file in the profile, you need to use a function. Call the function in your macro in this manner, where GetFolderPath is the function name:

Set Items = GetFolderPath("New PST\Test Cal").Items

After adding the function to ThisOutlookSession:

Function GetFolderPath(ByVal FolderPath As String) As Outlook.Folder
    Dim oFolder As Outlook.Folder
    Dim FoldersArray As Variant
    Dim i As Integer
        
    On Error GoTo GetFolderPath_Error
    If Left(FolderPath, 2) = "\\" Then
        FolderPath = Right(FolderPath, Len(FolderPath) - 2)
    End If
    'Convert folderpath to array
    FoldersArray = Split(FolderPath, "\")
    Set oFolder = Application.Session.Folders.item(FoldersArray(0))
    If Not oFolder Is Nothing Then
        For i = 1 To UBound(FoldersArray, 1)
            Dim SubFolders As Outlook.Folders
            Set SubFolders = oFolder.Folders
            Set oFolder = SubFolders.item(FoldersArray(i))
            If oFolder Is Nothing Then
                Set GetFolderPath = Nothing
            End If
        Next
    End If
    'Return the oFolder
    Set GetFolderPath = oFolder
    Exit Function
        
GetFolderPath_Error:
    Set GetFolderPath = Nothing
    Exit Function
End Function

Written by

Diane Poremsky
A Microsoft Outlook Most Valuable Professional (MVP) since 1999, Diane is the author of several books, including Outlook 2013 Absolute Beginners Book. She also created video training CDs and online training classes for Microsoft Outlook. You can find her helping people online in Outlook Forums as well as in the Microsoft Answers and TechNet forums.

If the Post Coment button disappears, press your Tab key.