我不是Outlook VBA的专家,但我设法创建了一些效果很好的宏。我已经在下面的代码上工作了一段时间,现在我遇到了一个小问题。宏将每个电子邮件的信息从共享收件箱的子文件夹导入到Excel文件中。我遇到的问题是for for next循环遇到非邮件项目(例如会议邀请或传递失败通知)。代码在“下一行”行停止,并在遇到这些非邮件项时出现“类型不匹配”错误。再次按播放将继续代码,直到它遇到另一个非邮件项目。我想让代码跳过这些非邮件项目并循环遍历整个收件箱/文件夹。
我尝试了“On Error Resume Next”,但它似乎跳过了“Next”行并继续使用其余代码而没有实际循环回“For Each”行。我玩过If和GoTo语句,但没有一个对我有用。有人可以帮忙吗?
我的宏也有另一个问题。有时它不会运行,因为它似乎无法识别收件箱的“ARCHIVE”子文件夹,但有时它很好。我的猜测是,当共享收件箱与服务器等同步时,无法访问“ARCHIVE”文件夹,但这只是猜测。如果有人能够对这个问题有所了解,我也会非常感激。
Sub EmailStatsV3()
Dim olMail As Outlook.MailItem
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("Shared Inbox") 'Change "Shared Inbox" to whatever shared inbox you use
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 5)
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
End If
Next olMail
'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
答案 0 :(得分:1)
更改
Dim olMail As Outlook.MailItem
到
Dim olMail As Variant
应该使用Variant
类型来迭代For Each
循环中的集合,在您的示例中Next
项不是MailItem
- 这就是olMail的用途宣称为。您已经检查了olMail
是否是邮件项目,因此您可以在此处使用变体。