Search code examples
vbaoutlookmailitem

Can I iterate through all Outlook emails in a folder including sub-folders?


I have a folder which contains a number of emails and sub-folders. Within those sub-folders are more emails.

I'd like to write some VBA which will iterate through all emails in a certain folder, including those in any of the sub-folders. The idea is to extract the SenderEmailAddress and SenderName from every email and do something with it.

I've tried just exporting the folder as CSV with only these two fields and whilst this works, it doesn't support exporting emails held in sub-folders. Hence the need to write some VBA.

Before I go re-inventing the wheel, does anyone have any code snippets or links to sites which, given a folder name, shows how to get a MailItem object for every email in that folder and subsequent sub-folders?


Solution

  • Something like this ...

     Private Sub processFolder(ByVal oParent As Outlook.MAPIFolder)
    
            Dim oFolder As Outlook.MAPIFolder
            Dim oMail As Outlook.MailItem
    
            For Each oMail In oParent.Items
    
            'Get your data here ...
    
            Next
    
            If (oParent.Folders.Count > 0) Then
                For Each oFolder In oParent.Folders
                    processFolder oFolder
                Next
            End If
    End Sub