I am fetching emails within a timeframe from MS Outlook to populate a sheet of Excel.
Using Items.Restrict(filterstring)
to constrain the results to between two datetime stamps.
This works for intervals like 6/14/2024 23:59 and 6/15/2024 23:59 (daylong) returning the count of incoming Outlook items (emails, meeting invites, reports, etc.).
Intervals like 6/15/2024 4:50 and 6/15/2024 23:59 incorrectly return 0 results, as validated against Outlook.
'Has the nescessary Outlook variable declarations and references. DateTime vars strT and EndT
restrictfilter = "[ReceivedTime] > '" & Format(CStr(strtT), "M/D/YYYY h:n") & "' AND [ReceivedTime] <= '" & Format(CStr(EndT), "M/D/YYYY h:n") & "'"
Set olItems = olFolder.Items.Restrict(restrictfilter)
allitemscount = olItems.Count
Include AMPM in the format.
Option Explicit
Private Sub ExtractEmail_Time()
Dim olFolder As folder
Dim olMail As MailItem
Dim i As Long
Dim restrictfilter As String
Dim olItems As Items
Dim allItemsCount As Long
Set olFolder = Session.GetDefaultFolder(olFolderInbox)
Dim strtT As Date
Dim endT As Date
strtT = "6/15/2024 4:50"
endT = "6/15/2024 23:59"
restrictfilter = "[ReceivedTime] > '" & Format(CStr(strtT), "M/D/YYYY h:n") & "' AND [ReceivedTime] <= '" & Format(CStr(endT), "M/D/YYYY h:n") & "'"
Set olItems = olFolder.Items.Restrict(restrictfilter)
allItemsCount = olItems.count
Debug.Print allItemsCount
restrictfilter = "[ReceivedTime] > '" & Format(CStr(strtT), "M/D/YYYY h:n ampm") & "' AND [ReceivedTime] <= '" & Format(CStr(endT), "M/D/YYYY h:n ampm") & "'"
Set olItems = olFolder.Items.Restrict(restrictfilter)
allItemsCount = olItems.count
Debug.Print allItemsCount
restrictfilter = "[ReceivedTime] > '" & Format(strtT, "M/D/YYYY h:n ampm") & "' AND [ReceivedTime] <= '" & Format(endT, "M/D/YYYY h:n ampm") & "'"
Set olItems = olFolder.Items.Restrict(restrictfilter)
allItemsCount = olItems.count
Debug.Print allItemsCount
restrictfilter = "[ReceivedTime] > '" & Format(strtT, "ddddd h:n ampm") & "' AND [ReceivedTime] <= '" & Format(endT, "ddddd h:n ampm") & "'"
Set olItems = olFolder.Items.Restrict(restrictfilter)
allItemsCount = olItems.count
Debug.Print allItemsCount
End Sub