Home > database >  Outlook .Restrict method doesn't filter calendar meetings by date correctly
Outlook .Restrict method doesn't filter calendar meetings by date correctly

Time:03-12

When trying to extract future calendar events from Outlook, the method Items.Restrict is not working as expected.

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 Immediate window showing wrong results

Any idea on why this is happening and how I can fix it?

CodePudding user response:

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") & "'"

CodePudding user response:

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
  • Related