I found this code that is able to extract Emails from a specified folder in Outlook into Excel. The issue is that sometimes it gives me the run time error -2147352567 (80020009)' when setting the subfolder item. For example, today it gave me the error but after 7 tries in one hour (just for testing), it worked. This behavior occurs randomly. Some days it works the first time then again it throws an error the next day and I have to keep running it till it works such as Today.
Sub EmailStatsV3()
Dim Item As Object
Dim varOutput() As Variant
Dim lngcount As Long
Dim xlApp As Excel.Application
Dim xlSht As Excel.Worksheet
Dim ShareInbox As Outlook.MAPIFolder
Dim olNs As Outlook.NameSpace
Dim olRecip As Outlook.Recipient
Dim SubFolder As Object
Set olNs = Application.GetNamespace("MAPI")
Set olRecip = olNs.CreateRecipient("[email protected]") '// Owner's Name or email address
Set ShareInbox = olNs.GetSharedDefaultFolder(olRecip, olFolderInbox)
Set SubFolder = ShareInbox.Folders("name").Folders("outages") 'Change this line to specify folder
ReDim varOutput(1 To SubFolder.Items.Count, 1 To 11)
For Each Item In SubFolder.Items
If TypeName(Item) = "MailItem" Then
lngcount = lngcount + 1
varOutput(lngcount, 1) = Item.SenderEmailAddress 'Sender or SenderName
varOutput(lngcount, 2) = Item.ReceivedTime 'stats on when received
varOutput(lngcount, 3) = Item.ConversationTopic 'Conversation subject
varOutput(lngcount, 4) = Item.Subject 'to split out prefix
varOutput(lngcount, 5) = Item.Categories 'to split out category
varOutput(lngcount, 6) = Item.Sender
varOutput(lngcount, 7) = Item.SenderName
varOutput(lngcount, 8) = Item.To
varOutput(lngcount, 9) = Item.CC
varOutput(lngcount, 10) = SubFolder.Name
varOutput(lngcount, 11) = Item.Body
End If
Next
'Creates a blank workbook in excel
Set xlApp = New Excel.Application
Set xlSht = xlApp.Workbooks.Add.Sheets(1)
xlSht.Range("A1").Resize(UBound(varOutput, 1), _
UBound(varOutput, 2)).Value = varOutput
xlApp.Visible = True
Set olNs = Nothing
Set olRecip = Nothing '// Owner's Name or email address
Set ShareInbox = Nothing
Set SubFolder = Nothing 'Change this line to specify folder
End Sub
Thank you,
Edit: This runtime error only occurs for me when accessing subfolders in shared default folders . A workaround was that I set the folder to current folder and it did the trick. For others facing similar issues, this is what I changed. You must remember to select the folder first.
Set SubFolder = Application.ActiveExplorer.CurrentFolder