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


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.


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