VBA loop with deleting items


I have the code below to loop through invited attendees in an outlook appointment and delete all of them, but it is not working as expected. After deleting one attendee it will then skip the next attendee and delete the one after that. E.g. If attendee one is deleted the code below will then skip attendee 2 and delete attendee 3 and so on. I am looking to have this so it deletes all attendees and not just every other one. Any suggestions?

For Each Item In RestrictedItems
  If Item.Class = olAppointment Then
    For Each Attendee in Item.Recipients
        Attendee.Delete
    Next Attendee

  
---------------Answer---------------

This issue is reported with monotonous regularity so it is surprising that your searches haven't led you to a solution. The issue you are experiencing occurs because you are changing the set of items that you are enumerating by deleting items. I.e when you delete item 2, what was item 3 now becomes item 2 BUT the counter in the VBA loop doesn't know that this has happened so increments to 3 and consequently the next item to be deleted is the current Item 3 (which was Item 4). This problem can be overcome by only deleting items outside the range that is left to be processed, i.e. deleting Item 7 is not an issue if you are counting down as item 6 will not have changed its position. Thus you need to use

For myIndex =Item.Recipients.Count to 1 Step -1 ' Because collections start at 1 not 0

    Item.Recipients.Item(myIndex).delete

Next


Previous : Collapsible element using javascript how to collapse by default
Next : Why this erlang prog with type signature can compile?