I have a strange issue on the below code I use for extracting Outlook email information into Excel. Sometimes the code works perfectly but other times I get the Run-Time Error '-2147221233 (8004010f)'. When I do get this error it is the line Set objFolder = objMailbox.Folders("Inbox").Folders("ARCHIVE") that has the issue.
I am running the code on a shared inbox and I have the "ARCHIVE" folder as a sub-folder of the inbox. It is as if the code cannot find the folder even though it is there and it can find it sometimes.
My uneducated guess is that, since a shared inbox can have a delay updating across all users, if there is any action in the folder the code cannot recognize the folder until it refreshes or updates on the server.
Can anybody suggest slightly different code so that it will run every time? Or does anybody have an explanation as to why it only occasionally works as is?
Sub EmailStatsV3()
'Working macro for exporting specific sub-folders of a shared inbox
Dim olMail As Variant
Dim aOutput() As Variant
Dim lCnt As Long
Dim xlApp As Excel.Application
Dim xlSh As Excel.Worksheet
Dim flInbox As Folder
'Gets the mailbox and shared folder inbox
Dim myNamespace As Outlook.NameSpace
Dim myRecipient As Outlook.Recipient
Set myNamespace = Application.GetNamespace("MAPI")
Set myRecipient = myNamespace.CreateRecipient("Operations")
Set objOutlook = CreateObject("Outlook.Application")
Set objNamespace = objOutlook.GetNamespace("MAPI")
Set objInbox = objNamespace.GetSharedDefaultFolder(myRecipient, olFolderInbox)
'Uses the Parent of the Inbox to specify the mailbox
strFolderName = objInbox.Parent
'Specifies the folder (inbox or other) to pull the info from
Set objMailbox = objNamespace.Folders(strFolderName)
Set objFolder = objMailbox.Folders("Inbox").Folders("ARCHIVE") 'Change this line to specify folder
Set colItems = objFolder.Items
'Specify which email items to extract
ReDim aOutput(1 To objFolder.Items.Count, 1 To 10)
For Each olMail In objFolder.Items
If TypeName(olMail) = "MailItem" Then
lCnt = lCnt + 1
aOutput(lCnt, 1) = olMail.SenderEmailAddress 'Sender or SenderName also gives similar output
aOutput(lCnt, 2) = olMail.ReceivedTime 'stats on when received
aOutput(lCnt, 3) = olMail.ConversationTopic 'group based on subject w/o regard to prefix
aOutput(lCnt, 4) = olMail.Subject 'to split out prefix
aOutput(lCnt, 5) = olMail.Categories 'to split out category
aOutput(lCnt, 6) = olMail.Sender
aOutput(lCnt, 7) = olMail.SenderName
aOutput(lCnt, 8) = olMail.To
aOutput(lCnt, 9) = olMail.CC
aOutput(lCnt, 10) = objFolder.Name
End If
Next
'Creates a blank workbook in excel then inputs the info from Outlook
Set xlApp = New Excel.Application
Set xlSh = xlApp.Workbooks.Add.Sheets(1)
xlSh.Range("A1").Resize(UBound(aOutput, 1), UBound(aOutput, 2)).Value = aOutput
xlApp.Visible = True
End Sub
I am assuming you are running the code from Outlook, see the cleanup I did.
Option Explicit
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("0m3r#Email.com") '// Owner's Name or email address
Set ShareInbox = olNs.GetSharedDefaultFolder(olRecip, olFolderInbox)
Set SubFolder = ShareInbox.Folders("Temp") 'Change this line to specify folder
ReDim varOutput(1 To SubFolder.Items.Count, 1 To 10)
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
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
End Sub
Related
I'd like to get some attributes from emails stored in a local folder. I know how to do it for emails in Outlook.folder but I guess the methods are not the same in that case.
I can't find a way to work with the .msg items as if they were emails.
I haven't try anything since I understand the problem comes from object class incompatibility, but I don't know what to use. Also, I couldn't find a guide on ".msg" item, could be useful
Private Sub email_listing()
On Error GoTo ErrHandler
' SET Outlook APPLICATION OBJECT.
Dim objOutlook As Object
Set objOutlook = CreateObject("Outlook.Application")
' CREATE AND SET A NameSpace OBJECT.
Dim objNSpace As Object
' THE GetNameSpace() METHOD WILL REPRESENT A SPECIFIED NAMESPACE.
Set objNSpace = objOutlook.GetNamespace("MAPI")
' CREATE A FOLDER OBJECT.
Dim myFolder, fs As Object
Set fs = CreateObject("Scripting.FileSystemObject")
Set myFolder = fs.GetFolder("C:\Users\boris\Desktop\Mail Test\")
Dim Item As Object
Dim iRows, iCols As Integer
iRows = 2
' LOOP THROUGH EACH ITEM IN THE FOLDER.
For Each Item In myFolder.Files
If Item.Type = "Outlook Item" Then
Dim objMail As Outlook.MailItem
Set objMail = Item 'THE BUG
Cells(iRows, 1) = objMail.SenderEmailAddress
Cells(iRows, 2) = objMail.To
Cells(iRows, 3) = objMail.Subject
Cells(iRows, 4) = objMail.ReceivedTime
Cells(iRows, 5) = objMail.Body
End If
iRows = iRows + 1
Next
Set objMail = Nothing
' RELEASE.
Set objOutlook = Nothing
Set objNSpace = Nothing
Set myFolder = Nothing
ErrHandler:
Debug.Print Err.Description
End Sub
I expect to have the attributes for each mail in my spreadsheet.
So far the code stop at line 27
Use Namespace.OpenSharedItem to open standalone MSG files.
I'm trying to write a VBA script to gather metrics on a shared mailbox throughout the day. Essentially, I'm wanting to export to Excel how many new, sent, and received messages where detected at different times throughout the day.
I'm working with the code below, however am getting an error when I try running the script. The error states:
"Run-time error '13'" Type mismatch"
Debugging highlights the error at Next olMail.
Does anyone have any ideas on what is causing this error, or if I need to be going at this from another direction? Also, I don't believe I have this setup correctly for my shared mailbox, as my default email is not shared. How do I need to modify Application.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox) for the script to recognize I need it to read the shared box?
I'm using Outlook 2013.
Sub EmailStats()
Dim olMail As MailItem
Dim aOutput() As Variant
Dim lCnt As Long
Dim xlApp As Excel.Application
Dim xlSh As Excel.Worksheet
Dim flInbox As Folder
Set flInbox = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
ReDim aOutput(1 To flInbox.Items.Count, 1 To 4)
For Each olMail In flInbox.Items
If TypeName(olMail) = "MailItem" Then
lCnt = lCnt + 1
aOutput(lCnt, 1) = olMail.SenderEmailAddress
aOutput(lCnt, 2) = olMail.ReceivedTime
aOutput(lCnt, 3) = olMail.ConversationTopic
aOutput(lCnt, 4) = olMail.Subject
End If
Next olMail
Set xlApp = New Excel.Application
Set xlSh = xlApp.Workbooks.Add.Sheets(1)
xlSh.Range("A1").Resize(UBound(aOutput, 1), UBound(aOutput, 2)).Value = aOutput
xlApp.Visible = True
End Sub
I figure if I can get the above to work, I can piece together the rest in Excel, though if anyone knows a better way any advice is definitely appreciated.
Lastly, where would I start if I'd like to add the ability to the script to export this information for individual sub-folders and/or categories? Is this possible?
Any point in the right direction I would be very grateful for.
Using the answer given by #Dmitry Streblechenko on this link:Get reference to additional Inbox
I've included the ResolveDisplayNameToSMTP function by Sue Mosher to wrap around the SenderEmailAddress.
Sub EmailStats()
Dim olMail As MailItem
Dim aOutput() As Variant
Dim ns As Outlook.NameSpace
Dim vRecipient As Recipient
Dim lCnt As Long
' Dim xlApp As Excel.Application
' Dim xlSh As Excel.Worksheet
Dim flInbox As Folder
Set ns = Application.GetNamespace("MAPI")
Set vRecipient = ns.CreateRecipient("<top level folder of shared inbox>")
If vRecipient.Resolve Then
Set flInbox = ns.GetSharedDefaultFolder(vRecipient, olFolderInbox)
End If
ReDim aOutput(1 To flInbox.Items.Count, 1 To 4)
For Each olMail In flInbox.Items
If TypeName(olMail) = "MailItem" Then
lCnt = lCnt + 1
aOutput(lCnt, 1) = ResolveDisplayNameToSMTP(olMail.SenderEmailAddress, Outlook.Application)
aOutput(lCnt, 2) = olMail.ReceivedTime
aOutput(lCnt, 3) = olMail.ConversationTopic
aOutput(lCnt, 4) = olMail.Subject
End If
Next olMail
' Set xlApp = New Excel.Application
' Set xlSh = xlApp.Workbooks.Add.Sheets(1)
' xlSh.Range("A1").Resize(UBound(aOutput, 1), UBound(aOutput, 2)).Value = aOutput
' xlApp.Visible = True
End Sub
'----------------------------------------------------------------------------------
' Procedure : ResolveDisplayNameToSMTP
' Author : Sue Mosher - updated by D.Bartrup-Cook to work in Excel late binding.
'-----------------------------------------------------------------------------------
Public Function ResolveDisplayNameToSMTP(sFromName, OLApp As Object) As String
Select Case Val(OLApp.Version)
Case 11 'Outlook 2003
Dim oSess As Object
Dim oCon As Object
Dim sKey As String
Dim sRet As String
Set oCon = OLApp.CreateItem(2) 'olContactItem
Set oSess = OLApp.GetNamespace("MAPI")
oSess.Logon "", "", False, False
oCon.Email1Address = sFromName
sKey = "_" & Replace(Rnd * 100000 & Format(Now, "DDMMYYYYHmmss"), ".", "")
oCon.FullName = sKey
oCon.Save
sRet = Trim(Replace(Replace(Replace(oCon.Email1DisplayName, "(", ""), ")", ""), sKey, ""))
oCon.Delete
Set oCon = Nothing
Set oCon = oSess.GetDefaultFolder(3).Items.Find("[Subject]=" & sKey) '3 = 'olFolderDeletedItems
If Not oCon Is Nothing Then oCon.Delete
ResolveDisplayNameToSMTP = sRet
Case 14 'Outlook 2010
Dim oRecip As Object 'Outlook.Recipient
Dim oEU As Object 'Outlook.ExchangeUser
Dim oEDL As Object 'Outlook.ExchangeDistributionList
Set oRecip = OLApp.Session.CreateRecipient(sFromName)
oRecip.Resolve
If oRecip.Resolved Then
Select Case oRecip.AddressEntry.AddressEntryUserType
Case 0, 5 'olExchangeUserAddressEntry & olExchangeRemoteUserAddressEntry
Set oEU = oRecip.AddressEntry.GetExchangeUser
If Not (oEU Is Nothing) Then
ResolveDisplayNameToSMTP = oEU.PrimarySmtpAddress
End If
Case 10, 30 'olOutlookContactAddressEntry & 'olSmtpAddressEntry
ResolveDisplayNameToSMTP = oRecip.AddressEntry.Address
End Select
End If
Case Else
'Name not resolved so return sFromName.
ResolveDisplayNameToSMTP = sFromName
End Select
End Function
I'm working on a project were I need a macro in outlook that will scan through the inbox for an e-mail with a "reference number" contained with-in the subject field. If no e-mail was detected, the system can then move on to the next reference from an excel spreadsheet.
If an e-mail was detected, it gets extracted as an "MSG" file and the actual e-mail moved into a subfolder. So far I have a code for extracting the e-mails as "MSG" files but I cant get it to identify the specific string (reference No) in the subject field. I got the below EXCEL Macro code so far from this site.
Sub Work_with_Outlook()
Set outlookApp = CreateObject("Outlook.Application")
Dim olNs As Outlook.NameSpace
Dim Fldr As Outlook.MAPIFolder
Dim olMail As Variant
Dim sir() As String
Set outlookApp = New Outlook.Application
Set olNs = outlookApp.GetNamespace("MAPI")
Set Fldr = olNs.GetDefaultFolder(olFolderInbox)
Set myTasks = Fldr.Items
Set olMail = myTasks.Find("[Subject] = ""Macro""")
If Not (olMail Is Nothing) Then
olMail.Display
End If
End Sub
Try below code:
Sub SaveAttachments()
Dim myOlapp As Outlook.Application
Dim myNameSpace As Outlook.Namespace
Dim myFolder, destFolder As Outlook.MAPIFolder
Dim i, lr As Long
'last used row in excel
lr = Cells(Rows.Count, "A").End(xlUp).Row
Set myOlapp = GetObject(, "Outlook.application")
Set myNameSpace = myOlapp.GetNamespace("MAPI")
Set myFolder = myNameSpace.GetDefaultFolder(olFolderInbox)
Set destFolder = myFolder.Folders("provide subFolderName here")
Set mytask = myFolder.Items
'Download and move attachment if found
For i = 1 To lr
'The below line of code will not work if you are using wild card or partial string
Set ref = mytask.Find("[Subject] =" & Range("a" & i).Value)
If Not (ref Is Nothing) Then
ref.Attachments.Item(1).SaveAsFile "C:\" & Range("a" & i).Value & ".msg"
ref.Move destFolder
End If
Set ref = Nothing
'The workaround code goes as below
For Each myItem In mytask
If myItem.Class = olMail Then
If InStr(1, myItem.Subject, Range("a" & i).Value) > 0 Then
myItem.Attachments.Item(1).SaveAsFile "C:\" & Range("a" & i).Value & ".msg"
myItem.Move destFolder
End If
End If
Next myItem
Next i
Set myOlapp = Nothing
Set myNameSpace = Nothing
Set myFolder = Nothing
Set destFolder = Nothing
Set mytask = Nothing
End Sub
Note: Assuming reference number is in "A" Column
I have two email address. The first is address1#domain.com.vn and the second is address2#domain.com.vn.
I want to copy email subject in microsoft outlook with second address address2#domain.com.vn to excel using vba. I use bellow code but it do not work.
Sub GetFromInbox()
Dim olapp As Outlook.Application
Dim olNs As Namespace
Dim Fldr As MAPIFolder
Dim olMail As Variant
Dim Pst_Folder_Name
Dim MailboxName
'Dim date1 As Date
Dim i As Integer
Sheets("sheet1").Visible = True
Sheets("sheet1").Select
Cells.Select
Selection.ClearContents
Cells(1, 1).Value = "Date"
Set olapp = New Outlook.Application
Set olNs = olapp.GetNamespace("MAPI")
Set Fldr = olNs.ActiveExplorer.CurrentFolder.Items
MailboxName = "address2#domain.com.vn"
Pst_Folder_Name = "Inbox"
Set Fldr = Outlook.Session.Folders(MailboxName).Folders(Pst_Folder_Name)
i = 2
For Each olMail In Fldr.Items
'For Each olMail In olapp.CurrentFolder.Items
ActiveSheet.Cells(i, 1).Value = olMail.ReceivedTime
ActiveSheet.Cells(i, 3).Value = olMail.Subject
ActiveSheet.Cells(i, 4).Value = olMail.SenderName
i = i + 1
Next olMail
End Sub
try this
Sub GetFromInbox()
Dim olapp As Outlook.Application
Dim olNs As Outlook.Namespace
Dim Fldr As Outlook.MAPIFolder
Dim olMail As Outlook.MailItem
Dim Pst_Folder_Name As String, MailboxName As String
Dim i As Long
MailboxName = "address2#domain.com.vn"
Pst_Folder_Name = "Inbox"
Set olapp = New Outlook.Application
Set olNs = olapp.GetNamespace("MAPI")
Set Fldr = olNs.Folders(MailboxName).Folders(Pst_Folder_Name)
With Sheets("sheet1")
.Cells.ClearContents
.Cells(1, 1).Value = "Date"
i = 2
For Each olMail In Fldr.Items
'For Each olMail In olapp.CurrentFolder.Items
.Cells(i, 1).Value = olMail.ReceivedTime
.Cells(i, 3).Value = olMail.Subject
.Cells(i, 4).Value = olMail.SenderName
i = i + 1
Next olMail
End With
olapp.Quit
Set olapp = Nothing
End Sub
If your using ActiveExplorer.CurrentFolder then you don't need to set your email Inbox, code should run on currently displayed folder in explorer.
Example
Option Explicit
Public Sub Example()
Dim Folder As MAPIFolder
Dim CurrentExplorer As Explorer
Dim Item As Object
Dim App As Outlook.Application
Dim Items As Outlook.Items
Dim LastRow As Long, i As Long
Dim xlStarted As Boolean
Dim Book As Workbook
Dim Sht As Worksheet
Set App = Outlook.Application
Set Folder = App.ActiveExplorer.CurrentFolder
Set Items = Folder.Items
Set Book = ActiveWorkbook
Set Sht = Book.Worksheets("Sheet1")
LastRow = Sht.Range("A" & Sht.Rows.Count).End(xlUp).Row
i = LastRow + 1
For Each Item In Items
If Item.Class = olMail Then
Sht.Cells(i, 1) = Item.ReceivedTime
Sht.Cells(i, 2) = Item.SenderName
Sht.Cells(i, 3) = Item.Subject
i = i + 1
Book.Save
End If
Next
Set Item = Nothing
Set Items = Nothing
Set Folder = Nothing
Set App = Nothing
End Sub
I am trying to import details of every email (sender, received time, subject etc.) in my Inbox into an Excel file. I have code that works fine for a specific folder within the Inbox but my Inbox has several subfolders, and these subfolders also have subfolders.
After much trial and error I have managed to import details of all subfolders under the Inbox. However the code does not import the emails from the 2nd tier of subfolders and it also skips the emails that are still in the Inbox itself. I have searched this site and others but cannot find the code to loop through all folders and subfolders of an Inbox.
For example I have an Inbox with subfolders Reports, Pricing and Projects.
The Report subfolder has subfolders called Daily, Weekly and Monthly. I can import the emails in Reports but not in Daily, Weekly and Monthly.
My code as it stands is below:
Sub SubFolders()
Dim olMail As Variant
Dim aOutput() As Variant
Dim lCnt As Long
Dim xlSh As Excel.Worksheet
Dim olApp As Outlook.Application
Dim olNs As Folder
Dim olParentFolder As Outlook.MAPIFolder
Dim olFolderA As Outlook.MAPIFolder
Dim olFolderB As Outlook.MAPIFolder
Set olApp = New Outlook.Application
Set olNs = olApp.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
Set olParentFolder = olNs
ReDim aOutput(1 To 100000, 1 To 5)
For Each olFolderA In olParentFolder.Folders
For Each olMail In olFolderA.Items
If TypeName(olMail) = "MailItem" Then
On Error Resume Next
lCnt = lCnt + 1
aOutput(lCnt, 1) = olMail.SenderEmailAddress
aOutput(lCnt, 2) = olMail.ReceivedTime
aOutput(lCnt, 3) = olMail.Subject
aOutput(lCnt, 4) = olMail.Sender
aOutput(lCnt, 5) = olMail.To
End If
Next
Next
Set xlApp = New Excel.Application
Set xlSh = xlApp.Workbooks.Add.Sheets(1)
xlSh.Range("A1").Resize(UBound(aOutput, 1), UBound(aOutput, 2)).Value = aOutput
xlApp.Visible = True
End Sub
From this question Can I iterate through all Outlook emails in a folder including sub-folders?
Replace your attempt to iterate the folders ...
For Each olFolderA In olParentFolder.Folders
For Each olMail In olFolderA.Items
If TypeName(olMail) = "MailItem" Then
On Error Resume Next
lCnt = lCnt + 1
aOutput(lCnt, 1) = olMail.SenderEmailAddress
aOutput(lCnt, 2) = olMail.ReceivedTime
aOutput(lCnt, 3) = olMail.Subject
aOutput(lCnt, 4) = olMail.Sender
aOutput(lCnt, 5) = olMail.To
End If
Next
Next
...using the idea of recursion described in the currently accepted answer.
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 ' <--- no brackets around oFolder
Next
End If
End Sub
The fleshed out second answer shows how to declare variables outside of the code to pass values.
Option Explicit
Dim aOutput() As Variant
Dim lCnt As Long
Sub SubFolders()
'
' Code for Outlook versions 2007 and subsequent
' Declare with Folder rather than MAPIfolder
'
Dim xlApp As Excel.Application
Dim xlSh As Excel.Worksheet
Dim olNs As Namespace
Dim olParentFolder As Folder
Set olNs = GetNamespace("MAPI")
Set olParentFolder = olNs.GetDefaultFolder(olFolderInbox)
lCnt = 0
ReDim aOutput(1 To 100000, 1 To 5)
ProcessFolder olParentFolder
On Error Resume Next
Set xlApp = GetObject(, "Excel.Application")
On Error GoTo 0
If xlApp Is Nothing Then Set xlApp = CreateObject("Excel.Application")
Set xlSh = xlApp.Workbooks.Add.Sheets(1)
xlSh.range("A1").Resize(UBound(aOutput, 1), UBound(aOutput, 2)).Value = aOutput
xlApp.Visible = True
ExitRoutine:
Set olNs = Nothing
Set olParentFolder = Nothing
Set xlApp = Nothing
Set xlSh = Nothing
End Sub
Private Sub ProcessFolder(ByVal oParent As Folder)
Dim oFolder As Folder
Dim oMail As Object
For Each oMail In oParent.Items
If TypeName(oMail) = "MailItem" Then
lCnt = lCnt + 1
aOutput(lCnt, 1) = oMail.SenderEmailAddress
aOutput(lCnt, 2) = oMail.ReceivedTime
aOutput(lCnt, 3) = oMail.Subject
aOutput(lCnt, 4) = oMail.Sender
aOutput(lCnt, 5) = oMail.To
End If
Next
If (oParent.Folders.count > 0) Then
For Each oFolder In oParent.Folders
ProcessFolder oFolder
Next
End If
End Sub