Outlook – List all top level folders using VBA

How do we list top level folders using VBA? I wanted to list all the top level folders such as LargeOldEmails, LargeOldEmails2 etc.

Outlook 2010 top level folders

Outlook 2010 top level folders

In Outlook, ensure that the Developer tab is enabled. Click Alt + F11 or click on Developer tab and click Visual Basic.

After reaching the Visual Basic for Applications (VBA) window, click CTRL + G to show the Immediate Window. This is where we will publish debug messages.

' We will explicitly declare all variables using
' Dim or ReDim keywords. This is good practice
Option Explicit

' List all accounts I have in Outlook
Sub ListAccounts()

    ' Let's get the current application's session
    Dim Session As Outlook.NameSpace
    Set Session = Application.Session

    ' Now let's get top level accounts. They are
    ' folders according to Outlook
    Dim Folders As Outlook.Folders
    Set Folders = Session.Folders

    ' Now that we have a collection of folders, let's
    ' list each folder's name
    Dim Folder As Outlook.Folder
    For Each Folder In Folders
        Debug.Print Folder.Name
    Next

End Sub

Click within the ListAccounts() macro and press F5 to run. The Debug.Print statement will show name of the folders in the immediate window. If you want to run the macro again, first click inside the Immediate Window, select all text and delete it. Running the macro over and over again will continue to fill the Immediate Window and the most recently printed line will be at the bottom. To avoid scrolling, it is best to clean up the Immediate Window before running the macro ListAccounts().