我正在尝试在Outlook中找到一封电子邮件,其中包含特定主题并从该电子邮件下载附件,但我无法做到。
我使用的是带限制函数的变量,但问题似乎是因为使用了通配符。您能告诉我从特定主题行开始查找电子邮件的最佳方法吗?以下是我正在使用的代码:
Sub findemail()
cntofmkts = Range("A" & Rows.Count).End(xlUp).Row
cntofmkts = cntofmkts - 1
ftodaydate = Format(Date, "yyyy-mm-dd")
Do
If i > cntofmkts Then Exit Do
MarketName = Range("A" & j).Value
Findvariable = "XXX_" & MarketName & "_ABC_" & ftodaydate
For Each oOlItm In oOlInb.Items.Restrict("[Subject] = *Findvariable*")
eSender = oOlItm.SenderEmailAddress
dtRecvd = oOlItm.ReceivedTime
dtSent = oOlItm.CreationTime
sSubj = oOlItm.Subject
sMsg = oOlItm.Body
If oOlItm.Attachments.Count <> 0 Then
For Each oOlAtch In oOlItm.Attachments
'~~> Download the attachment
oOlAtch.SaveAsFile NewFileName & oOlAtch.Filename
Exit For
Next
Else
MsgBox "The First item doesn't have an attachment"
End If
Exit For
Next
i = i + 1
j = j + 1
Loop
End sub
答案 0 :(得分:3)
首先要注意的是Restrict()
方法不会根据它的名称来评估变量。您必须将变量连接到字符串。
另一个是,如果您查看MSDN site中的示例,您将看到不支持通配符,因此您必须使用SQL语法,并且过滤器表达式中的搜索文本必须在引号之间。
' this namespace is for Subject
filterStr = "@SQL=""http://schemas.microsoft.com/mapi/proptag/0x0037001f"" like '%" & Findvariable & "%'"
似乎urn:schemas:httpmail:subject
也有效并且更容易理解,但我现在无法确认:
filterStr = "@SQL=""urn:schemas:httpmail:subject"" like '%" & Findvariable & "%'"
答案 1 :(得分:2)
DASL过滤器支持的字符串比较包括等价,前缀,短语和子字符串匹配。
对于每个oOlItm in oOlInb.Items.Restrict(&#34; [Subject] = Findvariable &#34;)
您似乎在搜索完全匹配。但您需要的是使用以下语法查找子字符串:
"[Subject] like '%" & Findvariable & "%'"
请注意,当您对Subject属性进行过滤时,前缀如&#34; RE:&#34;和&#34; FW:&#34;被忽略了。
有关详细信息,请参阅Filtering Items Using a String Comparison。
P.S。 Restrict方法是使用Find方法或FindNext方法迭代集合中特定项的替代方法。如果存在少量项目,则Find或FindNext方法比过滤更快。如果集合中有大量项目,则Restrict方法会明显加快,特别是如果预计只能找到大集合中的少数项目。