Im trying to create a simple VBA that:
- looks at my outlook account
- looks in all folders
- for the last 30 days
- creates simple excel summary of the email traffic showing simple fields (sender, date, email from, folder, etc)
Have created the below but it only pulls one folder and then exits.
I was expecting the code to loop through all folders in y inboxc but it didnt
Sub ExportEmailsToExcel()
Dim outlookApp As Outlook.Application
Dim outlookNamespace As Outlook.Namespace
Dim folder As Outlook.MAPIFolder
Dim subfolder As Outlook.MAPIFolder
Dim item As Object
Dim mailItem As Outlook.mailItem
Dim xlApp As Object
Dim xlWorkbook As Object
Dim xlWorksheet As Object
Dim row As Integer
Set outlookApp = New Outlook.Application
Set outlookNamespace = outlookApp.GetNamespace("MAPI")
Set folder = outlookNamespace.Folders("[email protected]")
' Create a new Excel workbook
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
Set xlWorkbook = xlApp.Workbooks.Add
Set xlWorksheet = xlWorkbook.Sheets(1)
' Set up the header row in Excel
xlWorksheet.Cells(1, 1).Value = "Date Received"
xlWorksheet.Cells(1, 2).Value = "From"
xlWorksheet.Cells(1, 3).Value = "From Email Address"
xlWorksheet.Cells(1, 4).Value = "Subject"
xlWorksheet.Cells(1, 5).Value = "Email Folder Location"
xlWorksheet.Cells(1, 6).Value = "Has Attachments"
row = 2
' Loop through all subfolders
For Each subfolder In folder.Folders
For Each item In subfolder.Items
If TypeName(item) = "MailItem" Then
Set mailItem = item
If mailItem.SenderEmailAddress = "[email protected]" Then
xlWorksheet.Cells(row, 1).Value = mailItem.ReceivedTime
xlWorksheet.Cells(row, 2).Value = mailItem.SenderName
xlWorksheet.Cells(row, 3).Value = mailItem.SenderEmailAddress
xlWorksheet.Cells(row, 4).Value = mailItem.Subject
xlWorksheet.Cells(row, 5).Value = subfolder.FolderPath
xlWorksheet.Cells(row, 6).Value = IIf(mailItem.Attachments.Count > 0, "True", "False")
row = row + 1
End If
End If
Next item
Next subfolder
MsgBox "Export complete!", vbInformation
' Clean up
Set xlWorksheet = Nothing
Set xlWorkbook = Nothing
xlApp.Quit
Set xlApp = Nothing
Set folder = Nothing
Set outlookNamespace = Nothing
Set outlookApp = Nothing
End Sub
New contributor
BarDar1967 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.