首页 > 解决方案 > 将 Outlook 项目限制为今天的日期 - VBA

问题描述

我编写了一些代码来扫描我的默认 Outlook 收件箱,以查找今天收到的具有特定主题的电子邮件。

然后,我下载符合我条件的 Outlook 项目的附件。我无法指定 Restrict 方法以撤回今天收到的项目。

这是我所拥有的:

Sub DownloadAttachmentFirstUnreadEmail()

Dim oOlAp As Object, oOlns As Object, oOlInb As Object
Dim oOlItm As Object, oOlAtch As Object
Dim sFilter As String
Dim NewFileName As String

NewFileName = "C:\Temp\" & "CHG_Daily_Extract_" & Format(Date, "MM-DD-YYYY") & ".csv"

'~~> Get Outlook instance
Set oOlAp = GetObject(, "Outlook.application")
Set oOlns = oOlAp.GetNamespace("MAPI")
Set oOlInb = oOlns.GetDefaultFolder(olFolderInbox)

'Declare email item restriction
sFilter = "[ReceivedTime] = '" & Format(Date, "DDDDD HH:NN") & "'"

'Catch
If oOlInb.Items.Restrict(sFilter).Count > 0 Then


'~~> Loop thru today's emails
For Each oOlItm In oOlInb.Items.Restrict(sFilter)

    '~> Check if the email subject matches
    If oOlItm = "ASG CDAS Daily CHG Report" Then

     '~~> Download the attachment
     For Each oOlAtch In oOlItm.Attachments
              oOlAtch.SaveAsFile NewFileName
            Exit For
        Next
        End If

    Exit For
Next

'Display if no emails today
Else: MsgBox "No items"

End If
End Sub

当我运行代码时,我一直收到“无项目”的捕获消息。

如果我错误地使用了 Restrict 方法,请告诉我。非常感谢你的帮助。

标签: vbaoutlookoutlook-filter

解决方案


以下怎么样——

Filter = "@SQL=" & "%today(" & Chr(34) & ("urn:schemas:httpmail:datereceived") & _
                               Chr(34) & ")%

或带附件

Filter = "@SQL=" & "%today(" & Chr(34) & ("urn:schemas:httpmail:datereceived") & _
                               Chr(34) & ")% AND " & _
                               Chr(34) & "urn:schemas:httpmail:hasattachment" & _
                               Chr(34) & "=1"

例子

Option Explicit
Private Sub Examples()
    Dim olNs As Outlook.NameSpace
    Dim Inbox As Outlook.MAPIFolder
    Dim Items As Outlook.Items
    Dim Msg As String
    Dim i As Long
    Dim Filter As String

    Set olNs = Application.GetNamespace("MAPI")
    Set Inbox = olNs.GetDefaultFolder(olFolderInbox)

    Filter = "@SQL=" & "%today(" & Chr(34) & ("urn:schemas:httpmail:datereceived") & _
                                   Chr(34) & ")%"


    Set Items = Inbox.Items.Restrict(Filter)

    Msg = Items.Count & " Items in " & Inbox.Name

    If MsgBox(Msg, vbYesNo) = vbYes Then
        For i = Items.Count To 1 Step -1
            Debug.Print Items(i) 'Immediate Window
        Next
    End If
End Sub

使用日期时间比较过滤项目 MSDN

Outlook 日期时间宏

下面列出的日期宏返回过滤字符串,将给定日期时间属性的值与指定的 UTC 日期进行比较;SchemaName 是命名空间引用的任何有效日期时间属性。

注意 Outlook 日期时间宏只能在 DASL 查询中使用。

宏语法说明

  1. today %today(" SchemaName")% 限制 SchemaName 属性值等于今天的项目

更多示例在这里


推荐阅读