【问题标题】:Find an email with subject starting with specific text查找主题以特定文本开头的电子邮件
【发布时间】:2015-05-26 16:39:05
【问题描述】:

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

我正在使用带有 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

【问题讨论】:

    标签: excel vba outlook outlook-filter


    【解决方案1】:

    您首先应该注意的是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 & "%'"
    

    【讨论】:

    • 搜索 PR_NORMALIZED_SUBJECT (0x0E1D001F) 而不是 PR_SUBJECT 可能会更好。
    • "@SQL=""urn:schemas:httpmail:subject"" like '%" & Findvariable & "%'" 和 "@SQL=urn:schemas:httpmail:subject like '% " & Findvariable & "%'" (没有引号) 在 Outlook 2010 中为我工作
    【解决方案2】:

    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 了解更多信息。

    附: Restrict 方法是使用 Find 方法或 FindNext 方法迭代集合中特定项的替代方法。如果项目数量很少,则 Find 或 FindNext 方法比过滤更快。如果集合中有大量项目,则 Restrict 方法的速度会明显加快,尤其是在预计只能找到大型集合中的少数项目的情况下。

    【讨论】:

    • 在 Outlook 2010 中不起作用:“无效条件”。我必须使用 SQL:"@SQL=urn:schemas:httpmail:subject like '%" & Findvariable & "%'"
    • Filtering Items Using a String Comparison 页面描述了各种方式。
    猜你喜欢
    • 2019-01-06
    • 2018-01-02
    • 2022-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多