Count the number of folders in your mailbox with Outlook VBA


A coworker asked me today if I knew how to count up the total number of folders in his mailbox, in the process of troubleshooting a bug related to having a large number of folders. I had an old script that recursed through a mailbox to count the total number of items (also written for the purposes of troubleshooting a bug many years ago where two clients showed different item counts, a lot of my macros start out that way 🙂 so I modified it to count folders and figured I’d share it.


Disclaimer: I performed a small amount of testing on this and it seems to be OK, but it wasn’t extensive – let me know if you find a bug.


And of course, like all of my macros, it has no error checking and may forget to declare variables before using them, yadda yadda 🙂

Sub CountFoldersInMBX()


Dim outapp As Outlook.Application
Set outapp = CreateObject(“Outlook.Application”)
Dim olns As Outlook.NameSpace
Set olns = outapp.GetNamespace(“MAPI”)


MsgBox “Total: ” & GetSubFolderCount(olns.GetDefaultFolder(olFolderInbox).Parent)

End Sub


Function GetSubFolderCount(objParentFolder As MAPIFolder) As Long

 


Dim currentFolders As Folders
Dim fldCurrent As MAPIFolder


Set currentFolders = objParentFolder.Folders
If currentFolders.Count > 0 Then
   Set fldCurrent = currentFolders.GetFirst
   While Not fldCurrent Is Nothing
      TempFolderCount = TempFolderCount + GetSubFolderCount(fldCurrent)
      Set fldCurrent = currentFolders.GetNext
   Wend
   GetSubFolderCount = TempFolderCount + currentFolders.Count
Else
    GetSubFolderCount = 0
End If


End Function


Comments (2)

  1. Anonymous says:

    Easy Free Way To Remove Duplicate Contacts From Microsoft Outlook Q&A: Exchange 2003 backup and recovery

  2. Anonymous says:

    Just ran across your very useful site, thanks! Here’s an odd and only tangentially related question. If I assign a macro (this one or any of the others from the blog) to a keyboard shortcut, it works for every shortcut I try EXCEPT Alt-B. A little more experimentation shows that I can’t remap Alt-B to *anything* including word built-ins like WordLeft or WordDelete. What gives?  This is Outlook 2003 SP2, 11.8118.8132 if that means anything.

    Thanks,

    Dave