Restrict Outlook Items by Date

You can find yesterday’s mail with two separate Restricts.

Private Sub EmailYesterday()

Dim oOlInb As Folder
Dim oOlItm As Object

Dim oOlResults As Object
Dim i As Long

Dim sFilter As String
Dim sFilter2 As String

Set oOlInb = Session.GetDefaultFolder(olFolderInbox)

'Filter recent - Lower Bound of the range
sFilter = "[ReceivedTime]>'" & format(Date - 1, "DDDDD HH:NN") & "'"

Debug.Print vbCr & sFilter
Set oOlResults = oOlInb.Items.Restrict(sFilter)
Debug.Print oOlResults.count & " items."

If oOlResults.count > 0 Then
    For i = 1 To oOlResults.count
        Set oOlItm = oOlResults(i)
        Debug.Print oOlItm.Subject & " - " & oOlItm.ReceivedTime
    Next i
End If

' Filter range - Upper Bound
sFilter2 = "[ReceivedTime]<'" & format(Date, "DDDDD HH:NN") & "'"

Debug.Print vbCr & sFilter; " AND " & sFilter2

Set oOlResults = oOlResults.Restrict(sFilter2)   ' Restrict the Lower Bound result
Debug.Print oOlResults.count & " items."

If oOlResults.count > 0 Then
    For i = 1 To oOlResults.count
        Set oOlItm = oOlResults(i)
        Debug.Print oOlItm.Subject & " - " & oOlItm.ReceivedTime
    Next i
End If
    
ExitRoutine:
    Set oOlInb = Nothing
    Set oOlResults = Nothing
    Debug.Print "Done."
    
End Sub

Leave a Comment