In VBA, there is no built-in “List” object like in .NET; the closest equivalents are the Collection object and the ArrayList (from the .NET Framework, accessible via mscorlib.dll), and for most tasks the Collection is the right choice. This guide explains how to create, populate, and iterate over these list-like structures, when to use each, and how to avoid common pitfalls.
What VBA Offers for Storing Lists
VBA provides several ways to hold an ordered set of items. The most direct is the Collection object, which is built into VBA and requires no references. It allows you to add items, retrieve them by index or by a unique key, and remove them. A Collection automatically resizes as you add items, so you don’t need to declare a fixed size.
Another option is the ArrayList, which comes from the .NET Framework and is available in VBA by adding a reference to mscorlib.dll. ArrayLists offer more methods (like Sort, Reverse, and Contains) and are more flexible than Collections, but they require the reference and are slightly slower for simple tasks.
For completeness, a plain VBA array (e.g., Dim myList() As String) can also act as a list if you manage its size with ReDim Preserve, but this is clunky and error-prone for dynamic data. This article focuses on Collection and ArrayList because they are the true “list” objects.
Using the Collection Object
The Collection is the simplest way to manage a list in VBA. Here is a basic example that adds three names and prints them:
Sub DemoCollection()
Dim col As New Collection
col.Add "Alice"
col.Add "Bob"
col.Add "Charlie"
Dim i As Integer
For i = 1 To col.Count
Debug.Print col(i)
Next i
End Sub
Key points about Collections:
- Items are stored as
Variant, so you can mix types (strings, numbers, objects). - Indexing starts at 1, not 0.
- You can add a unique string key to each item:
col.Add "Alice", "A"and later retrieve withcol("A"). - Removing an item uses
col.Remove(index)orcol.Remove(key). - You cannot easily sort a Collection; you must write your own sorting routine or copy to an array.
Using the ArrayList (with .NET Reference)
To use ArrayList, go to Tools > References in the VBA editor and check mscorlib.dll. Then you can create an ArrayList and use its methods:
Sub DemoArrayList()
Dim list As Object
Set list = CreateObject("System.Collections.ArrayList")
list.Add "Banana"
list.Add "Apple"
list.Add "Cherry"
' Sort alphabetically
list.Sort
Dim item As Variant
For Each item In list
Debug.Print item
Next item
End Sub
ArrayList advantages:
- Built-in
Sort,Reverse,Contains, andIndexOfmethods. - Indexing starts at 0.
- You can use
For Eachjust like a Collection. - It can hold mixed types, but sorting mixed types may throw an error.
Disadvantages: requires the reference, which may not be available on all systems (though mscorlib is standard on Windows). Also, it is not native VBA, so some users avoid it for portability.
How to Choose Between Collection and ArrayList
For most VBA projects, the Collection is the best default because it requires no references and is simple. Use ArrayList when you need sorting or searching without writing custom code. Here is a quick guide:
- Need a simple list with add/remove? → Collection.
- Need to sort the list? → ArrayList.
- Need to check if an item exists? → ArrayList’s
Containsis easier than looping a Collection. - Working with objects? Both work, but Collection allows keys for fast lookup.
- Sharing your code with others? Collection is safer because no reference setup is needed.
If you stick with Collection, you can always convert to an array for sorting using a simple loop, but that adds code.
Common Problems and How to Avoid Them
Here are typical issues when working with lists in VBA:
- Off-by-one errors: Collection indexes start at 1, ArrayList at 0. Always check the Count property.
- Adding duplicate keys: If you try to add an item with a key that already exists, you get a runtime error 457. Check with a function or use a different key.
- Modifying a Collection while iterating: You cannot remove items inside a
For Eachloop. Instead, collect indices to remove in a separate array and then remove them after the loop. - ArrayList not found: If you forget to set the reference,
CreateObjectmay fail. Ensure mscorlib is referenced. - Sorting mixed types: Sorting an ArrayList with numbers and strings throws an error. Keep types consistent.
For example, to safely remove items from a Collection while iterating:
Sub RemoveEvenNumbers(col As Collection)
Dim toRemove As New Collection
Dim i As Integer
For i = 1 To col.Count
If col(i) Mod 2 = 0 Then toRemove.Add i
Next i
For i = toRemove.Count To 1 Step -1
col.Remove toRemove(i)
Next i
End Sub
This avoids the “collection was modified” error.
Alternatives: Dictionaries and Arrays
If your list has unique keys, a Dictionary (from Microsoft Scripting Runtime) is often better because it allows fast lookup by key. However, a Dictionary is not a list; it is a key-value pair collection. Use it when you need to associate values with keys.
Plain arrays are useful when the size is known in advance or when performance is critical. You can use ReDim Preserve to resize, but this is inefficient for large lists because it copies the entire array each time. For most dynamic lists, Collection or ArrayList is preferable.
Performance and Memory Considerations
Collections and ArrayLists are both dynamic and handle resizing automatically, but they have overhead. For very large lists (tens of thousands of items), a Collection can become slow due to internal resizing. In such cases, consider using an array with a single ReDim after counting items, or use a Dictionary if keys are involved.
Memory-wise, Collections store each item as a Variant, which can be larger than a typed array. If you are storing simple numbers, an array of Long or Double is more memory-efficient. However, for typical Excel automation tasks, the difference is negligible.
Always save a copy of your workbook before running any macro that modifies data, because macros cannot be undone with Ctrl+Z. Test your list code on a small sample first.
Frequently Asked Questions
How do I create a list in VBA without a reference?
Use the Collection object. It is built-in, so no reference is needed. Just declare Dim myList As New Collection and start adding items.
Can I sort a Collection in VBA?
No built-in sort exists for Collection. You can copy the items to an array, sort the array (using a simple bubble sort or the Sort method of ArrayList), and then rebuild the Collection. Or use ArrayList directly for sorting.
What is the difference between a Collection and an ArrayList in VBA?
Collection is native, uses 1-based indexing, and supports keys. ArrayList requires a reference to mscorlib, uses 0-based indexing, and provides methods like Sort and Contains. Collection is simpler; ArrayList is more feature-rich.
How do I remove an item from a Collection by value?
You must loop through the Collection to find the index of the matching value, then remove that index. For example: For i = 1 To col.Count: If col(i) = "Bob" Then col.Remove i: Exit For: Next i.
Is there a way to check if an item exists in a Collection?
No built-in Contains method. You can loop through all items and compare, or use a Dictionary with keys for O(1) lookup. For ArrayList, use the Contains method.
Can I store objects in a Collection?
Yes, Collections store any Variant, including object references. When retrieving, you may need to use Set if you assign to an object variable, e.g., Set ws = col(1).
Related
- Google Dividend Per Share: Current Rate & History
- Python Enum Multiple Values: How to Use Them
- Enums in Python 3: A Complete Guide
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- Excel VBA Option Explicit: What It Does and How to Use ItOption Explicit is a VBA module setting that requires you to declare variables before using them. Put it…
- Excel VBA Protect Sheet Allow Format CellsYes, you can protect a worksheet in Excel VBA while still allowing users to format cells. Use the…
- VBA Delete Blank Rows in Excel: Safe MethodsYes. In Excel for Microsoft 365 on Windows, a VBA macro can scan a chosen range from bottom…
- Excel VBA Calendar Date Picker: Options and SetupExcel for Microsoft 365 on Windows does not include a universal VBA calendar date-picker control that you can…
- Excel VBA Input Box With a Drop-Down ListExcel’s built-in VBA InputBox cannot display a drop-down list. To let someone choose from fixed options, create a…
- VBA Loop Through Cells: Methods and ExamplesTo loop through cells in Excel VBA, use For Each for a specified range or a counter-based For…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.