Excel VBA Collection Add: How to Use It Correctly
In this article
Using Excel VBA's Collection.Add method lets you store multiple related items — like strings, numbers, or objects — in a single, ordered group that you can loop through or reference by key. Unlike arrays, collections allow you to assign custom keys and don't require pre-declaring size. This is essential for dynamic data handling in macros, such as tracking user input, managing worksheet references, or building lookup tables. Before you begin, ensure you're working in the VBA editor (Alt+F11) with a workbook that allows macros, and that you understand basic VBA syntax like declaring variables and using Sub procedures.
What You'll Need
- Microsoft Excel with macro support enabled (file saved as .xlsm or .xlsb)
- Access to the Visual Basic for Applications editor (press Alt+F11)
- A basic understanding of variable declaration in VBA
- A workbook with data you want to collect or manage programmatically
Step-by-Step
- Open Excel and press Alt+F11 to launch the VBA Editor.
- In the Project Explorer (left panel), right-click your workbook name and choose Insert > Module to create a new code module.
- Declare a new Collection variable by typing:
Dim myCollection As Collectionat the top of your module or inside your Sub procedure. - Initialize the collection using
Set myCollection = New Collection. This must be done before adding items — omitting this causes a runtime error. - Use the Add method to insert items. The basic syntax is:
myCollection.Add Item:=value, Key:="myKey". For example:myCollection.Add Item:="Apple", Key:="Fruit1". - Repeat step 5 for each item you want to add. You can add numbers, cell references, or even other objects like Range or Worksheet. For instance:
myCollection.Add Item:=Range("A1"), Key:="FirstCell". - To add an item without a key, use only the Item parameter:
myCollection.Add "Banana". Items without keys are accessed by numeric index starting at 1. - Test your collection by looping through it. Use a For Each loop:
For Each item In myCollection: Debug.Print item: Next item. This prints each value to the Immediate Window (Ctrl+G in VBA editor). - Save your workbook as a macro-enabled file (.xlsm) before closing. If you save as .xlsx, your VBA code will be removed.
Common Mistakes
- Forgetting to use
Setwhen initializing the Collection — this causes a ‘Variable not defined’ or ‘Object required’ error. - Using duplicate keys. If you try to add two items with the same key (e.g., both "Fruit1"), VBA throws error 457: "This key is already associated with an element of this collection".
- Trying to access a key that doesn’t exist. Use
On Error Resume Nextor check existence with a helper function to avoid runtime crashes. - Confusing index-based access with key-based access. Items without keys are numbered 1, 2, 3...; items with keys are accessed by key, not position.
- Adding objects without explicitly qualifying their scope — e.g., adding a Range without specifying the worksheet can cause reference errors if sheets are renamed or deleted.
Tips
- Always use meaningful keys like "CustomerID_123" instead of "Key1" — this makes debugging and code maintenance much easier.
- Use the Collection’s Count property to check how many items you’ve added:
Debug.Print myCollection.Count. - For large datasets, collections are faster than arrays when you need to insert or remove items dynamically.
- Store worksheet references in a collection to avoid hardcoding sheet names:
myCollection.Add Item:=Sheets("Sales"), Key:="SalesData". - If you need to remove items later, use
myCollection.Remove "Key"ormyCollection.Remove 1for index-based removal. - Use the Immediate Window (Ctrl+G) during development to print values and verify your collection contents in real time.
- Never use spaces or special characters like /, \, :, or * in keys — they’re not allowed and will trigger errors.
Troubleshooting
- If you get error 91 (Object variable not set), ensure you used
Set myCollection = New Collection. This is the most frequent cause. - If you get error 457 (key already exists), check your code for duplicate keys. You can use a loop to verify uniqueness before adding:
If Not KeyExists(myCollection, newKey) Then myCollection.Add .... - If your collection appears empty after adding items, make sure you’re not declaring a new collection inside a loop — each iteration would overwrite the previous one.
- If you can’t access an item by key, confirm the key string matches exactly, including case. VBA keys are case-sensitive: "Apple" ≠ "apple".
- If your macro crashes when accessing a Range stored in the collection, ensure the worksheet still exists and hasn’t been renamed or deleted during runtime.
- If the VBA editor won’t let you run the macro, check that macros are enabled in Excel: File > Options > Trust Center > Trust Center Settings > Macro Settings > Enable all macros (for development only).
Frequently Asked Questions
Can I add arrays to a Collection?
Yes, you can add entire arrays as single items. For example:Dim arr() As String: arr = Array("A", "B", "C"): myCollection.Add arr. Access the array later using For Each element In myCollection(1) — but remember the array is stored as one object.
Can I store objects like Worksheets or Ranges in a Collection?
Yes. UsemyCollection.Add Item:=Sheets("Sheet1"), Key:="MainSheet". This lets you loop through sheets or reference them without hardcoding names.
What if I need to remove an item from the Collection?
UsemyCollection.Remove "Key" to remove by key, or myCollection.Remove 1 to remove the first item by index. Removal shifts subsequent items' indices down.
Are Collections faster than Arrays in VBA?
For dynamic data, yes — adding or removing items doesn’t require ReDim Preserve. For large static sets, arrays are faster to iterate. Choose based on your use case.Can I use Collection with user-defined types or classes?
Yes. You can add instances of custom classes or user-defined types as long as they are declared as objects. For example:Dim emp As Employee: Set emp = New Employee: myCollection.Add emp.
Why can’t I use a number as a key?
Keys must be strings. Even if you want to use a numeric ID, convert it:Key:=CStr(1001). VBA does not accept numeric literals as keys.