Reputation: 55
I am trying to extract future calendar events from Outlook using the Items.Restrict
method.
If the filter is not applied, it returns more than 70 results, older and future events.
When the filter for future events is applied, it returns around 20 results, most of them, future events, but also some old ones.
The Restrict filter is partially working, but I cannot understand why is not filtering those few old events.
Dim oOutlook As Object
Dim oMAPI As Object
Dim oAppointments As Object
Dim oFilteredAppointments As Object
Dim oAppointmentItem As Object
Dim sFilter As String
Const olFolderCalendar = 9
Set oOutlook = GetObject(, "Outlook.Application")
Set oMAPI = oOutlook.GetNamespace("MAPI")
Set oAppointments = oMAPI.GetDefaultFolder(olFolderCalendar)
sFilter = "[Start]>'" & Date & "'"
Debug.Print sFilter
Set oFilteredAppointments = oAppointments.Items.Restrict(sFilter)
For Each oAppointmentItem In oFilteredAppointments
Debug.Print oAppointmentItem.Start
Next
To show some evidence of the filter and the results I'm getting:
Upvotes: 0
Views: 1350
Reputation: 9179
Calendars are trickier than normal folders. I had to combine the two filters as was suggested in Restrict Outlook Items by Date.
Note: oAppointmentItems
rather than oAppointments.Items
.
Option Explicit
Private Sub calApptsInSpecifiedRange()
Dim oCalendarFolder As Folder
Dim oAppointmentItems As Items
Dim oFilteredAppointments As Items
Dim oAppointmentItem As Object
Dim sFilter As String
Set oCalendarFolder = Session.GetDefaultFolder(olFolderCalendar)
Set oAppointmentItems = oCalendarFolder.Items
oAppointmentItems.Sort "[Start]", False
oAppointmentItems.IncludeRecurrences = True
sFilter = "[Start] > '" & Date & "'" & " AND [Start] < " & "'" & Date + 30 & "'"
Debug.Print sFilter
Set oFilteredAppointments = oAppointmentItems.Restrict(sFilter)
For Each oAppointmentItem In oFilteredAppointments
Debug.Print oAppointmentItem.Start, oAppointmentItem.Subject
Next
Debug.Print "Done."
End Sub
Upvotes: 2
Reputation: 49395
To retrieve all Outlook appointment items from the folder that meets the predefined condition, you need to sort the items in ascending order and set the IncludeRecurrences
to true. You will not catch recurrent appointments if you don’t do this before using the Restrict method. Read more about that in the How To: Use Restrict method in Outlook to get calendar items article.
Also you may find the How To: Retrieve Outlook calendar items using Find and FindNext methods article helpful.
Dates and times are typically stored with a Date
format, the Find
and Restrict
methods require that the date and time be converted to a string representation. To make sure that the date is formatted as Microsoft Outlook expects, use the Format function. The following example creates a filter to find all contacts that have been modified after January 15, 2022 at 3:30 P.M.
sFilter = "[LastModificationTime] > '" & Format("1/15/2022 3:30pm", "ddddd h:nn AMPM") & "'"
Upvotes: 0