Skip to content

Outlook VBA: Iterate recursively over folders

May 31st, 2016 - SoftwareTutorial(1 min)

Note: This is a post transferred from Laurii for historical and consolidation purposes.

As part of the program I’ve started, I had to perform a recursive walking of all sub-folders from a starting point in a .pst file. Code looks like this:

Sub WalkFolders(fnum)

    Dim olApp As Outlook.Application
    Dim olSession As Outlook.NameSpace
    Dim olStartFolder As Outlook.MAPIFolder

    lCountOfFound = 0

    Set olApp = New Outlook.Application
    Set olSession = olApp.GetNamespace("MAPI")

    ' Allow the user to pick the folder in which to start the search.
    Set olStartFolder = olSession.PickFolder

    ' Check to make sure user didn't cancel PickFolder dialog.
    If Not (olStartFolder Is Nothing) Then
        ' Start the search process.
        ProcessFolder olStartFolder, fnum
    End If

    ' Pop up a dialog box at the end
    MsgBox "Done" & olStartFolder.FolderPath

End Sub

This doesn’t do too much… It selects a folder and calls a function. The recursive part is below:

' Parameters:
'  CurrentFolder: the current folder to walk
'  fnum         : the writeable file (see http://www.laurivan.com/outlook-vba-write-to-a-file/)
Sub ProcessFolder(CurrentFolder As Outlook.MAPIFolder, fnum)

    Dim i As Long
    Dim olNewFolder As Outlook.MAPIFolder
      ' late bind this object variable, since it could be various item types
    Dim olTempFolder As Outlook.MAPIFolder
    Dim olTempFolderPath As String

    ' Loop through the items in the current folder.
    ' Looping through backwards in case items are to be deleted,
    ' as this is the proper way to delete items in a collection.
    For i = CurrentFolder.Folders.Count To 1 Step -1

        Set olTempFolder = CurrentFolder.Folders(i)

        ' Do some post-processing for each item
    Next

    ' Call some generic function
    ProcessGeneric CurrentFolder, fnum

    ' Loop through and search each subfolder of the current folder.
    For Each olNewFolder In CurrentFolder.Folders

        'Don't need to process the Deleted Items folder
        If olNewFolder.name <> "Deleted Items" Then
            ' Call recursively the walking function
            ProcessFolder olNewFolder, fnum
        End If

    Next

End Sub

Now, you can process each item in the directory in the first loop and elegantly call a per-item processor (d’oh!). Other than that, VBA in Outlook 2003 is not nice… The tiniest mistake, you get an error. It doesn’t like something (like strings and objects), you get an error. Not nice after processing 100 emails to get something like Mismatched objects… Still, it’s quicker than doing a C# :(

Share on
Reddit
Linked in
Whatsapp

A little experiment: