On an Access form, I have an unbound 'unbCalendarUpdates_FromDate' field, an unbound 'unbCalendarUpdates_ToDate' field, and a 'btnCalendarUpdates' button. On the 'On Click' Event for the button, I have the following VBA code. What I'm trying to do is to delete all Appointments (lying within a specified date range) from my Microsoft Outlook Calendar. (Later, I'll be introducing VBA code for repopulating my Calendar with updated info held within my Access database).
At present, my Appointments are not being deleted. Can anyone help me understand why that's the case ? Thanks in advance for any guidance.
At present, my Appointments are not being deleted. Can anyone help me understand why that's the case ? Thanks in advance for any guidance.
Code:
Private Sub btnCalendarUpdates_Click()
Dim olApp As Object 'Late binding - No Outlook reference needed.
Dim olNS As Object
Dim olFolder As Object
Dim olItems As Object
Dim filteredItems As Object
Dim olAppt As Object
Dim filter As String
Dim i As Long
'Start Outlook if not already running
On Error Resume Next
Set olApp = GetObject(, "Outlook.Application")
If olApp Is Nothing Then
Set olApp = CreateObject("Outlook.Application")
End If
On Error GoTo 0
If olApp Is Nothing Then
MsgBox "Unable to start Outlook.", vbExclamation
Exit Sub
End If
Set olNS = olApp.GetNamespace("MAPI")
Set olFolder = olNS.GetDefaultFolder(9) ' 9 = olFolderCalendar
Set olItems = olFolder.Items
'Sort and include recurring appointments
olItems.Sort "[Start]"
olItems.IncludeRecurrences = True
Dim DateRange_From As Date
Dim DateRange_To As Date
DateRange_From = Me.unbCalendarUpdates_FromDate
DateRange_To = Me.unbCalendarUpdates_ToDate
'Construct the filter string
filter = "[Start] >= '" & Format(DateRange_From, "mm/dd/yyyy hh:nn AM/PM") & _
"' AND [Start] <= '" & Format(DateRange_To, "mm/dd/yyyy hh:nn AM/PM") & "'"
'Apply filter
Set filteredItems = olItems.Restrict(filter)
'Set oFilteredAppointments = oAppointmentItems.Restrict(sFilter)
'MsgBox "Count of filtered items : " & filteredItems.Count
'Loop backwards, to delete safely
For i = filteredItems.Count To 1 Step -1
Set olAppt = filteredItems.Item(i)
olAppt.Delete
Next i
End Sub