To add an item to a Collection in VBA, use the Add method: CollectionName.Add Item, [Key], [Before], [After]. For example, colNames.Add "Alice" appends “Alice” to the collection named colNames.
What Is a VBA Collection?
A Collection is a built-in VBA object that stores a set of items in an ordered list. Unlike an array, a Collection automatically grows when you add items, and you can insert or remove items without manually resizing. Collections are useful when you don’t know in advance how many items you’ll need, or when you want to associate a unique string key with each item for fast lookup.
Each item in a Collection can be any data type—a number, string, object, or even another Collection. The items are stored in the order you add them, unless you specify a position using the Before or After arguments.
How to Declare and Initialize a Collection
To use a Collection, you must first declare a variable of type Collection and then use the New keyword to create an instance. Here is the basic syntax:
Dim colItems As Collection
Set colItems = New Collection
You can also declare and initialize in one line:
Dim colItems As New Collection
Note: Using Dim colItems As New Collection automatically creates a new Collection the first time you reference it, but it can be less efficient because VBA checks each time whether the object is set. Most developers prefer the explicit Set approach for clarity and control.
Adding Items with the Add Method
The Add method has four optional arguments, but only the first is required. The full syntax is:
collection.Add item, [key], [before], [after]
Here’s what each argument does:
- item – the value or object you are adding (required).
- key – a unique string that identifies the item. Once set, you can retrieve the item using
collection("key"). - before – the position (1-based) or key of an existing item before which the new item is inserted.
- after – the position or key of an existing item after which the new item is inserted.
You cannot use both before and after at the same time—VBA will raise an error if you try.
Simple Example: Adding Names
Dim colNames As New Collection
colNames.Add "Alice"
colNames.Add "Bob"
colNames.Add "Charlie"
' Now colNames contains 3 items in order: Alice, Bob, Charlie
Adding with a Key
Dim colCars As New Collection
colCars.Add "Toyota", "car1"
colCars.Add "Honda", "car2"
' Retrieve by key:
MsgBox colCars("car2") ' Displays "Honda"
Keys are case-insensitive, meaning “CAR1” and “car1” refer to the same key. If you try to add a duplicate key, VBA raises error 457: “This key is already associated with an element of this collection.”
Inserting Items at a Specific Position
By default, items are appended to the end of the collection. To insert an item at a specific position, use the Before or After argument. The position is a 1-based index, so 1 is the first item.
Dim colNums As New Collection
colNums.Add 10
colNums.Add 30
colNums.Add 20, , 2 ' Insert 20 before the second item (30)
' Now order is: 10, 20, 30
You can also use a key to reference the existing item:
colNums.Add 25, , "second" ' Insert before item with key "second"
Note that if you use both before and after, VBA ignores both and simply appends the item—but it’s better to avoid that ambiguity.
Common Errors and How to Avoid Them
Here are the most frequent mistakes when adding items to a Collection:
- Duplicate key: Using the same key twice raises error 457. Always check if a key exists before adding, or use unique keys.
- Forgetting to Set: If you declare a Collection variable but don’t use
Set, you’ll get error 91: “Object variable or With block variable not set.” Always initialize withSet col = New Collection. - Using invalid Before/After: If the
BeforeorAfterindex is 0 or greater than the count, VBA raises error 5: “Invalid procedure call or argument.” The index must be between 1 and the collection’s Count. - Mixing data types: Collections are not type-safe; you can add a number and then a string. This is fine, but be careful when retrieving items—you may need to check the type with
TypeName.
Collection vs. Dictionary vs. Array
When deciding how to store data, consider these differences:
- Collection – simplest built-in object; supports keys and ordered insertion. Good for small to medium lists.
- Dictionary (from Microsoft Scripting Runtime) – faster for key lookups, and you can check if a key exists with
Exists. Requires adding a reference to “Microsoft Scripting Runtime” or using late binding. - Array – fixed size unless you use
ReDim Preserve, but it’s faster for indexed access and uses less memory. Good for large, static datasets.
For most simple tasks, a Collection is the easiest to work with. If you need to frequently look up items by a unique key, a Dictionary is more efficient.
Iterating Over a Collection
To loop through all items, use a For Each loop:
Dim colFruits As New Collection
colFruits.Add "Apple"
colFruits.Add "Banana"
Dim fruit As Variant
For Each fruit In colFruits
Debug.Print fruit
Next fruit
You can also use a For loop with the Count property and the Item method:
For i = 1 To colFruits.Count
Debug.Print colFruits(i)
Next i
Note that Item is the default property, so colFruits(i) works.
Frequently Asked Questions
Can I add a collection to another collection?
Yes, you can add a Collection object as an item in another Collection. For example:
Dim colOuter As New Collection
Dim colInner As New Collection
colInner.Add "A"
colOuter.Add colInner
' Access the inner item:
MsgBox colOuter(1)(1) ' Displays "A"
This is useful for creating hierarchical data structures.
How do I remove an item from a collection?
Use the Remove method, specifying either the index or the key. For example, colNames.Remove 1 removes the first item; colNames.Remove "key" removes the item with that key. Removing an item shifts all subsequent items up.
Can I add an item without specifying a key and later add a key?
No. The key is set only at the time of adding. Once an item is added without a key, you cannot assign a key later. If you need a key, you must include it in the Add call.
What happens if I use both Before and After?
VBA ignores both arguments and simply appends the item to the end of the collection. This is not an error, but it’s likely not what you intended. Always use only one of them.
Is there a limit to how many items a Collection can hold?
There is no built-in limit other than available memory. In practice, you can store hundreds of thousands of items, but performance may degrade with very large collections, especially when inserting in the middle.
Can I store objects (like Worksheets) in a Collection?
Yes, absolutely. Collections are often used to store object references. For example:
Dim colSheets As New Collection
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
colSheets.Add ws
Next ws
Then you can access colSheets(1).Name to get the first worksheet’s name.
Remember to always save a copy of your workbook before running any VBA macro, because macros cannot be undone with Ctrl+Z. Test your code in a module with a small dataset first to avoid unexpected errors.
Related
- Sitting and Standing Balance Grading Scale
- VA Data Entry & Administrative Support Explained
- Hotel Cash Flow Template Excel: How to Build One
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- Excel VBA: Loop Through Rows in a Range EfficientlyTo loop through every row in an Excel range with VBA, use For Each rowRange In dataRange.Rows when…
- Find Unique Values in VBA: Methods and ExamplesTo find distinct values in VBA, read the source cells into a Scripting.Dictionary and add a value only…
- Excel VBA Range.Formula: How to Read and Set FormulasIn Excel VBA, use a range’s Formula property to read or write a worksheet formula in A1 notation.…
- Excel VBA Macro to Sort Data: How to Write OneThe quickest way to sort data with an Excel VBA macro is to record a sort and then…
- Excel VBA Syntax Error: Causes, Examples, and FixesAn Excel VBA syntax error means the Visual Basic for Applications editor cannot parse part of your code…
- Excel VBA Hex String: Convert Numbers to HexadecimalIn Excel VBA, use the Hex function to turn a number into a hexadecimal string: Hex(255) returns FF.…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.