我想保存附件中具有特定文件扩展名的特定发件人的附件。我在循环的If部分遇到问题。我收到运行时错误438:对象不支持此属性或方法。
Sub GetAttachments()
Dim ns As NameSpace
Dim folder As Outlook.MAPIFolder
Dim Item As Object
Dim Atmt As Attachment
Dim FileName As String
Dim i As Integer
Set ns = GetNamespace("MAPI")
Set Inbox = ns.GetDefaultFolder(olFolderInbox)
i = 0
If Inbox.Items.Count = 0 Then
MsgBox "There are no messages in the Inbox.", vbInformation, _
"Nothing Found"
Exit Sub
End If
For Each Item In Inbox.Items
If Item.SenderEmailAddress = "email@domain.com" Then
For Each Atmt In Item.Attachments
' This path must exist! Change folder name as necessary.
If Right(Atmt.FileName, 3) = ".py" Then
FileName = "C:\Users\bill\Desktop\TEST\" & Atmt.FileName
Atmt.SaveAsFile FileName
i = i + 1
End If
Next Atmt
End If
Next Item
If i > 0 Then
MsgBox "I found " & i & " attached files." _
& vbCrLf & "I have saved them into the C:\Users\bill\Desktop\TEST folder." _
& vbCrLf & vbCrLf & "Have a nice day.", vbInformation, "Finished!"
Else
MsgBox "I didn't find any attached files in your mail." , vbInformation, "Finished!"
End If
GetAttachments_exit:
Set Atmt = Nothing
Set Item = Nothing
Set ns = Nothing
Exit Sub
GetAttachments_err:
MsgBox "An unexpected error has occurred." _
& vbCrLf & "Please note and report the following information." _
& vbCrLf & "Macro Name: GetAttachments" _
& vbCrLf & "Error Number: " & Err.Number _
& vbCrLf & "Error Description: " & Err.Description _
, vbCritical, "Error!"
Resume GetAttachments_exit
End Sub
答案 0 :(得分:2)
文件夹可以包含各种类型的项目。他们中的一些人没有提供SenderEmailAddress财产。尝试先检查项目类(或MessageCLass)。
如果您从其他应用程序自动化Outlook,也可能会出现安全问题。见Outlook "Object Model Guard" Security Issues for Developers。
并且不要对文件夹中的所有项目进行互动:
For Each Item In Inbox.Items
If Item.SenderEmailAddress = "email@domain.com" Then
您可以使用Items类的Find / FindNext或Restrict方法。请阅读以下文章中有关这些方法的更多信息:
另外,您可能会发现Application类的AdvancedSearch方法很有帮助。在Outlook中使用AdvancedSearch方法的主要好处是:
有关详细信息,请参阅Advanced search in Outlook programmatically: C#, VB.NET。
答案 1 :(得分:-2)
查看此示例
Filter = "[SenderEmailAddress] = 'email@domain.com'"
Set Items = Inbox.Items.Restrict(Filter)
ii = 0
For i = Items.Count To 1 Step -1
Set Item = Items.Item(i)
For Each Atmt In Item.Attachments
' This path must exist! Change folder name as necessary.
If Right(Atmt.FileName, 3) = ".py" Then
FilePath = "C:\Temp\"
FileName = Atmt.FileName
Atmt.SaveAsFile FilePath & FileName
ii = ii + 1
End If
Next Atmt
Next