Removing Objects from a Custom Collection

Removing an item from a custom collection is as easy as adding an item. To remove an element, use the Remove method in the following format:

object.Remove item

The object is the name of the custom collection that contains the item you want to remove. The item is the item you want to remove from the collection. To demonstrate the process of removing an item from a collection, let's work with the following hands-on that modifies the NewEmployees procedure that you prepared in Hands-On 8-1.

© Hands-On 8-2: Removing Objects from a Collection

This hands-on requires the prior completion of Hands-On 8-1.

1. Add the following lines to the NewEmployees procedure just before the End Sub keywords:

' remove the third element from the collection colEmployees.Remove (3)

MsgBox colEmployees.Count & " employees remain."

Reindexing Collections

Collections are reindexed automatically when an item is removed. Therefore, to remove all items from a custom collection you can use 1 for the Index argument, as in the following example:

Do While myCollection.Count >0 myCollection.Remove Index:=1


0 0

Post a comment