查找主题以特定文本开头的电子邮件

Find an email with subject starting with specific text

我正在尝试按以特定文本开头的主题查找电子邮件,然后从该电子邮件中下载附件。

我正在使用带有 Restrict 函数的变量,但问题似乎是因为使用了通配符。

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() 方法不会根据变量的名称计算变量。您必须将变量连接到字符串。

另一个是,如果您查看 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 & "%'"

DASL 过滤器支持的字符串比较包括等价、前缀、短语和子串匹配。

For Each oOlItm In oOlInb.Items.Restrict("[Subject] = Findvariable")

您似乎在搜索完全匹配的内容。但是您需要的是使用以下语法查找子字符串:

criteria = "@SQL=" & Chr(34) & "urn:schemas:httpmail:subject" & Chr(34) & " like '%question%'" 

请注意,当您过滤主题 属性 时,"RE: " 和 "FW: " 等前缀将被忽略。

有关详细信息,请参阅 Filtering Items Using a String Comparison

P.S。 Restrict 方法是使用 Find 方法或 FindNext 方法循环访问集合中特定项的替代方法。如果项目数量较少,则 Find 或 FindNext 方法比过滤更快。如果集合中有大量项目,Restrict 方法会明显更快,特别是如果预计只找到大型集合中的少数项目。