I am trying to write code that is going to add events to a calendar based on an excel sheet, but first it needs to delete any appointments that have the same subject as anything in my list. Here is my code:
When I run it, it doesn't always delete everything. It seems to delete a couple and then stop working. If I take away the error trapping, there is an error trying to delete because 'the object has moved or doesn't delete'. It happens on this line:
When I hover over oApptItem.Subject, it says this item has moved or been removed.
What is going on?
Thanks!
Code:
Dim oApp As Outlook.Application
Dim oNameSpace As Outlook.Namespace
Dim oApptItem As Outlook.AppointmentItem
Dim oFolder As Outlook.MAPIFolder
Dim oMeetingoApptItem As Outlook.MeetingItem
Dim oObject As Object
Dim iUserReply As VbMsgBoxResult
Dim sErrorMessage As String
Dim j As Integer
Dim i As Integer
On Error Resume Next
' check if Outlook is running
Set oApp = GetObject("Outlook.Application")
If Err <> 0 Then
'if not running, start it
Set oApp = CreateObject("Outlook.Application")
End If
On Error GoTo Err_Handler
Set oNameSpace = oApp.GetNamespace("MAPI")
Set oFolder = oNameSpace.GetDefaultFolder(olFolderCalendar)
On Error Resume Next
For Each oObject In oFolder.Items
If oObject.Class = olAppointment Then
Set oApptItem = oObject
For j = 2 To Range("A1").End(xlDown).Row
If InStr(oApptItem.Subject, Range("A" & j).Value) > 0 Then
oApptItem.Delete
End If
Next j
End If
Next oObject
On Error GoTo Err_Handler
For i = 2 To Range("A1").End(xlDown).Row
Set oApptItem = oApp.CreateItem(olAppointmentItem)
With oApptItem
.Subject = Range("A" & i).Value
.Start = Range("B" & i).Value
.AllDayEvent = True
.Save
.Send
End With
Next i
Set oApp = Nothing
Set oNameSpace = Nothing
Set oApptItem = Nothing
Set oFolder = Nothing
Set oObject = Nothing
Exit Sub
Err_Handler:
MsgBox ("Error running script. Did not run properly.")
End Sub
When I run it, it doesn't always delete everything. It seems to delete a couple and then stop working. If I take away the error trapping, there is an error trying to delete because 'the object has moved or doesn't delete'. It happens on this line:
Code:
If InStr(oApptItem.Subject, Range("A" & j).Value) > 0 Then
When I hover over oApptItem.Subject, it says this item has moved or been removed.
What is going on?
Thanks!