我使用以下vba代码,该代码应搜索具有特定主题标题的所有电子邮件,即主题为“test”
然后,只有当电子邮件未读时,才将该电子邮件中的附件保存到文件夹中。
可能有一个或多个电子邮件与主题测试,所以我希望所有未读电子邮件与主题测试将其附件保存到该文件夹。
这是我的代码:
Sub Work_with_Outlook()
Set olApp = CreateObject("Outlook.Application")
Dim olNs As Outlook.Namespace
Dim Fldr As Outlook.MAPIFolder
Dim myItem As Object
Dim myAttachment As Outlook.Attachment
Dim I As Long
Dim olMail As Variant
Set olApp = New Outlook.Application
Set olNs = olApp.GetNamespace("MAPI")
Set Fldr = olNs.GetDefaultFolder(olFolderInbox)
Set myTasks = Fldr.Items
Set UnRead = myTasks.Restrict("[UnRead] = False")
Set olMail = myTasks.Find("[Subject] = ""test""")
If Not (olMail Is Nothing) And UnRead.Count = 0 Then
For Each myItem In myTasks
If myItem.Attachments.Count <> 0 Then
For Each myAttachment In myItem.Attachments
If InStr(myAttachment.DisplayName, ".txt") Then
I = I + 1
myAttachment.SaveAsFile "\\uksh000-file06\Purchasing\NS\Unactioned\" & myAttachment
End If
Next
End If
Next
For Each myItem In myTasks
myItem.UnRead = False
Next
MsgBox "Scan Complete."
Else
MsgBox "There Are No New Supplier Requests."
End If
End Sub
这在某种程度上有效,如果我只有一封主题为'test'的电子邮件并且未读,那么脚本将从该电子邮件中获取附件并将其保存到我的文件夹中。但是,如果我有一封主题为'test'的电子邮件被读取,而另一封电子邮件主题'test'未读,那么该代码将不起作用?
有人可以告诉我哪里出错了吗?提前致谢
答案 0 :(得分:0)
看起来您需要将两个comdition组合成一个,并使用Find / FindNext或Restrict方法获取Items类的实例,其中包含与您的条件相对应的所有项目。例如:
Set resultItems = myTasks.Restrict("[UnRead] = False AND [Subject] = ""test""")
有关MSDN中的信息,请参阅Enumerating, Searching, and Filtering Items in a Folder。
您也可以在以下文章中找到示例代码: