此问题已在此处有答案:
type mismatch error on loop in vba(1个答案)
Type Mismatch in Loop to scan Outlook Messages [duplicate](1个答案)
5天前关闭。
我目前正在处理一个宏来抓取Outlook电子邮件和附件。有一个小的类型不匹配错误,希望有人能指出我需要什么数据类型。
所以我意识到在某些时候我需要面对一个很大的实用性障碍。现在我专注于让事情运转起来,然后优化。
Sub FetchEmailData()
Dim appOutlook As Object
Dim olNs As Object
Dim olFolder As Object
Dim olItem As Object
Dim iRow As Integer
' Get/create Outlook Application
On Error Resume Next
Set appOutlook = GetObject(, "Outlook.Application")
If appOutlook Is Nothing Then
Set appOutlook = CreateObject("Outlook.Application")
End If
On Error GoTo 0
Set olNs = appOutlook.GetNamespace("MAPI")
Set olFolder = olNs.GetDefaultFolder(6) ' 6 == Inbox for some reason
For iRow = 1 To olFolder.Items.Count
'Check if we care about the e-mail
Call SaveEmailAttachment(olFolder.Items.Item(iRow))
'Go onto the next one if we don't
'ThisWorkbook.Sheets("Test").Cells(iRow + 1, 1) = olFolder.Items.Item(iRow).SenderEmailAddress
'ThisWorkbook.Sheets("Test").Cells(iRow + 1, 2) = olFolder.Items.Item(iRow).Subject
'ThisWorkbook.Sheets("Test").Cells(iRow + 1, 3) = olFolder.Items.Item(iRow).To
'ThisWorkbook.Sheets("Test").Cells(iRow + 1, 3) = olFolder.Items.Item(iRow).Size
Next iRow
End Sub
Sub SaveEmailAttachment(itm As Outlook.MailItem)
Dim objAtt As Outlook.Attachment
Dim saveFolder As String
Dim dateFormat As String
saveFolder = ThisWorkbook.Names("EmailAttachmentSavePath").RefersToRange.Value2
dateFormat = Format(itm.ReceivedTime, "yyyy-mm-dd Hmm ")
For Each objAtt In itm.Attachments
objAtt.SaveAsFile saveFolder & "\" & dateFormat & objAtt.DisplayName
Next
End Sub
因此,数据类型不匹配是因为我正在发送Outlook文件夹项目,但接收宏需要Outlook MailItem
。我知道我需要将它们都设置为相同的项目类型,可能是通过dim
,但我不太确定哪一个更好,以及我需要如何调整SaveEmailAttachment
代码以进行适当补偿。
附加问题:有没有办法按名称抓取子文件夹?
1条答案
按热度按时间46qrfjad1#
测试TypeOf项,如果是mailItem,则传递它。