I mean to get all AppointmentItem
s in a Date
range and return them as a Collection.
This is the function I wrote
Function GetAppointmentItemsDatesRange(ByVal dstart As Date, ByVal dend As Date) As Outlook.Items
'=======================================================
' Get all AppointmentItem in a range of dates
'=======================================================
Dim oCalendar As Outlook.Folder
Set oCalendar = Application.Session.GetDefaultFolder(olFolderCalendar)
Dim objItems As Outlook.Items
Dim objRestrictedItems As Outlook.Items
Set objItems = oCalendar.Items
objItems.IncludeRecurrences = True
'objItems.IncludeRecurrences = False
objItems.Sort "[Start]"
Dim filterRange As String
filterRange = "[Start] >= " & Chr(34) & Format(dstart, "dd/mm/yyyy hh:mm AM/PM") & Chr(34) & " AND " & _
"[End] <= " & Chr(34) & Format(dend, "dd/mm/yyyy hh:mm AM/PM") & Chr(34) ' <-- Line #1'
Set objRestrictedItems = objItems.Restrict(filterRange)
Debug.Print "Filter : " & filterRange
Dim oItem As Outlook.AppointmentItem
Dim iIt As Long
Dim nItFilter As Long, nIt As Long
nItFilter = objRestrictedItems.Count
nIt = 0
Debug.Print nItFilter & " total items"
For Each oItem In objRestrictedItems
If (Not (oItem Is Nothing)) Then
nIt = nIt + 1
Debug.Print oItem.Start & "-" & oItem.End ' <-- Line #2'
End If
Next oItem
Debug.Print nIt & " net items"
Set GetAppointmentItemsDatesRange = objRestrictedItems
End Function
I tried with both .IncludeRecurrences = True
and False
.
This is the output I get.
False
:
Filter : [Start] >= "07/11/2020 05:30 PM" AND [End] <= "07/11/2020 06:15 PM"
9 total items
31/12/2015 9:00:00-31/12/2015 9:00:00
31/01/2017 15:30:00-31/01/2017 15:30:00
18/03/2020 12:00:00-18/03/2020 16:00:00
13/04/2020 8:45:00-13/04/2020 9:00:00
09/09/2020 11:00:00-09/09/2020 12:00:00
28/09/2020 14:45:00-28/09/2020 18:00:00
01/10/2020 13:30:00-01/10/2020 15:00:00
07/11/2020 17:30:00-07/11/2020 17:45:00
07/11/2020 17:45:00-07/11/2020 18:15:00
9 net items
True
:
Filter : [Start] >= "07/11/2020 05:30 PM" AND [End] <= "07/11/2020 06:15 PM"
2147483647 total items
07/11/2020 17:30:00-07/11/2020 17:45:00
07/11/2020 17:45:00-07/11/2020 18:15:00
2 net items
So I identify two problems to get to my result:
- The outputs of
Line #1
andLine #2
seem inconsistent, in both cases. I do not understand why are the first 7 items not filtered out in theFalse
case, even if I can get rid of them withTrue
. And I do not understand what are those too manyNothing
items in theTrue
case. - I do not know hot to define a Collection where I can add the items that satisfy the
If (Not (oItem Is Nothing))
condition, so I can return it upon exiting for the caller to use.
What is the explanation for the questions? How can I achieve my goal?