I am trying to delete all appointments from an Excel VBA (Excel 2010) macro but get an Error 13 (Type Mismatch) on the olFolder.Items.GetFirst. I can't explain why, since it run flawless a few weeks ago.
Anyone who can give me a hand with this error=
Here´s the VBA code:
Sub DeleteAllAppointments()
Dim olApp As Object
Application.ScreenUpdating = False
Set olApp = CreateObject("Outlook.Application")
Dim olApptItem As Outlook.AppointmentItem
Dim olMeetingItem As Outlook.MeetingItem
Dim olNameSpace As Outlook.Namespace
Dim olFolder As Outlook.MAPIFolder
Dim olObject As Object
Dim olItems As Items
Dim i As Double
Set olNameSpace = olApp.GetNamespace("MAPI")
Set olFolder = olNameSpace.GetDefaultFolder(olFolderCalendar)
Set olItems = olFolder.Items
Set olApptItem = olFolder.Items.GetFirst
For i = 1 To olItems.Count
If olItems.Count > 1 Then
olApptItem.Delete
Set olApptItem = olFolder.Items.GetNext
Else
Set olApptItem = olFolder.Items.GetLast
olApptItem.Delete
End If
Next
End Sub
Usually that means that you actually have some items in your folder that are not an Appointment item. You need to test what the item is before assuming that it is an appointment. This is true even when the folder is set to only contain appointment items.
When deleting items it's usually best to start high and iterate backwards. Delete as you go.
I know the request is a bit old, but I wanted to contribute with a code I have written which may help.
Please make sure the correct folder is selected (tmpCalendarFolder) before running the code... or at least make some tests before running on a "production" environment, as you are deleting items.
As already mentioned you should delete them in reverse order - as they are re-indexed each time and you eventually try to refer to an item that doesn't exist.
You don't need to
Set
the next item in the loop as you can useRemove(i)
to delete a particular item:However, this code will delete EVERY appointment, because practically everything within the calendar is an
AppointmentItem
. If you don't want to delete, for example, aMeeting
then you need to read some property such asMeetingStatus
, which is 1 for a Meeting and 0 for a Non-Meeting:From Excel though, using
olAppointment
may be preferable toAppointmentItem
because you can substitute the numeric value of 26 if necessary:If olItems(i).Class = 26
.