使用VBA查找以特定主题开始的电子邮件

我正在尝试从特定主题开始在Outlook中查找电子邮件,并从该电子邮件下载附件,但我无法做到这一点。

我正在使用具有限制function的variables,但问题似乎是由于使用通配符。 您能否让我知道从特定主题行开始查找电子邮件的最佳方法是什么? 以下是我正在使用的代码:

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 

你应该介意的第一件事是Restrict()方法不会通过它的名字来计算variables。 您必须将variables连接到string。

另一个问题是,如果您查看MSDN 站点的示例,则会看到不支持通配符,因此必须使用SQL语法,并且filterexpression式中的search文本必须位于引号之间。

 ' 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 & "%'" 

DASLfilter支持的string比较包括等同性,前缀,短语和子串匹配。

对于oOlInb.Items.Restrict中的每个项目(“[Subject] = Findvariable ”)

它看起来像你search完全匹配。 但是你需要的是使用下面的语法find一个子string:

 "[Subject] like '%" & Findvariable & "%'" 

请注意,在过滤Subject属性时,将忽略诸如“RE:”和“FW:”之类的前缀。

有关更多信息,请参阅使用string比较过滤项目 。

PS Restrict方法是使用Find方法或FindNext方法迭代集合中的特定项目的替代方法。 如果有less量项目,Find或FindNext方法比筛选更快。 如果集合中有大量项目,那么Restrict方法明显更快,特别是如果希望find大集合中的less数项目。