Items - Add / Remove

Members can be added before or after an existing member based on both the index number or a key value
All collections are 1 based.


Adding

Collection.Add (item [,key] [,before] [,after])
item - the item you want to add to the collection
key - a unique string that can be used instead of using the positional index
before - the relative position index (or key string) of the element to have in front of it.
after - the relative position index (or key string) of the element to have behind it.

oMyCol.Add "Mon" 
oMyCol.Add ("Tue")
oMyCol.Add "Mon", "M" ' include a key
oMyCol.Add ("Tue", "T") ' include a key

Adding Before

This adds "Wed" before "Mon"

oMyCol.Add "Mon" 
oMyCol.Add ("Tue")
oMyCol.Add "Wed", Before:=1 ' wed, mon, tue
oMyCol.Add "Thu", , 1 ' thu, wed, mon, tue

Adding After

This adds "Wed" after "Mon"

oMyCol.Add "Mon" 
oMyCol.Add ("Tue")
oMyCol.Add "Wed", After:=1 ' mon, wed, tue
oMyCol.Add "Thu", , , 1 ' mon, tue, wed, thu

Adding Using a Loop

Do not add items like this

For lrowno = 1 to 10 
   On Error Resume Next
   colMyCollection.Add Cells(lrowno,1).value, Cells(lrowno,2).Value
   On Error GoTo 0
Next lrowno

Adding Duplicates

The items in a collection do not have to be unique.

oMyCol.Add "Mon" 
oMyCol.Add "Mon"
oMyCol.Add "Mon"

When a key is not supplied the "key" field is left blank.
If a key has not been provided the only way to access the items is by their position.

Debug.Print oMyCol(1) 
Debug.Print oMyCol(1)
Debug.Print oMyCol(1)

You cannot identify or retrieve these items by key, because they don't have one.
If you do use keys, they must be unique.



Removing

Collection.Remove (index)
index - the relative position index (or key string) of the element you want to remove

Dim myCollection As VBA.Collection 
Set myCollection = New VBA.Collection
myCollection.Add "Item 1"
myCollection.Remove "Item 1"

Remove All

A collection does not have a RemoveAll
Set myCollection = Nothing
Multiple deletion using the index number should be done in descending order because the collection is reindexed every time.


© 2026 Better Solutions Limited. All Rights Reserved. © 2026 Better Solutions Limited TopPrevNext