在Outlook VBA中使用ReceivedTime来计算昨天的邮件

时间:2016-02-10 22:01:08

标签: vba email outlook

我想用昨天收到的邮件数量闪烁一个消息框。

我目前的代码是:

Public Sub YesterdayCount()

Set ns = Application.GetNamespace("MAPI")
Set outApp = CreateObject("Outlook.Application")
Set outNS = outApp.GetNamespace("MAPI")

Dim Items As Outlook.Items
Dim MailItem As Object

Dim yestcount As Integer
yestcount = 0

Set Folder = outNS.Folders("Correspondence Debt Advisor Queries").Folders("Inbox")
Set Items = Folder.Items

For Each Item In Items
    If MailItem.ReceivedTime = (Date - 1) Then
        yestcount = yestcount + 1
    End If
Next

MsgBox yestcount

End Sub

问题出在以下几行:

If MailItem.ReceivedTime = (Date - 1) Then

错误说没有设置对象变量,但在研究之后我无法理解它。

1 个答案:

答案 0 :(得分:3)

你几乎得到了它。您基本上从未设置MailItem或将其限定为Item,并且由于ReceivedTime是日期/时间格式,因此它永远不会等于直线Date

请参阅下面的代码。我添加了一些按ReceivedTime排序的功能,然后在昨天通过日期后退出循环。我还清理了一些变量命名,因此不会与固有的Outlook对象命名约定混淆。

Public Sub YesterdayCount()

Dim outNS As Outlook.NameSpace
Set outNS = Application.GetNamespace("MAPI")

Dim olFolder As Outlook.Folder
Set olFolder = outNS.Folders("Correspondence Debt Advisor Queries").Folders("Inbox")

Dim olItems As Outlook.Items
Set olItems = olFolder.Items

olItems.Sort "[ReceivedTime]", True

Dim yestcount As Integer
yestcount = 0

Dim item As Object

For Each item In olItems

    'commented code works for MailItems
    'Dim olMail As Outlook.MailItem
    'Set olMail = item

    Dim dRT As Date
    'dRT = olMail.ReceivedTime
    dRT = item.ReceivedTime

    If dRT < Date And dRT > Date - 2 Then
        If dRT < Date - 1 Then Exit For
        yestcount = yestcount + 1
    End If


Next

MsgBox yestcount

End Sub