VBA Arrays and Collections
Store and manage multiple values efficiently with arrays and collection objects
Quick Reference
Arrays: Store multiple values of same type in indexed list
Collections: Flexible objects that store any data type with keys
Dictionary: Key-value pairs (requires Scripting.Dictionary reference)
ArrayList: Dynamic list with built-in methods
What are Arrays?
Arrays are variables that can store multiple values in a single container, accessed by numeric index. Think of an array as a list of numbered boxes, each holding a value.
❌ Without Arrays:
Messy and unmanageable!
✓ With Arrays:
Clean and scalable!
Static Arrays
Fixed size arrays declared with specific dimensions.
Declaration Syntax:
Basic Example:
Loop Through Array:
Dynamic Arrays
Arrays that can be resized at runtime with ReDim.
Declaration and Resizing:
ReDim Preserve (Keep Existing Data):
Note: ReDim Preserve is slow for large arrays. Use Collections for dynamic lists instead!
Multi-Dimensional Arrays
Arrays with 2 or more dimensions (like Excel tables - rows and columns).
2D Array (Table Structure):
Load Excel Range to Array:
Loop Through 2D Array:
Useful Array Functions
| Function | Description | Example |
|---|---|---|
| LBound | Lowest index | LBound(arr) |
| UBound | Highest index | UBound(arr) |
| Split | String to array | Split("a,b,c", ",") |
| Join | Array to string | Join(arr, ", ") |
| Array | Quick array creation | Array(1, 2, 3) |
| Filter | Filter array | Filter(arr, "test") |
Split and Join Example:
Collection Object
VBA's built-in Collection object - flexible, dynamic, and easy to use.
Basic Collection Operations:
Collections with Keys:
Loop Through Collection:
When to Use Collections:
- ✓ Don't know size in advance
- ✓ Frequently adding/removing items
- ✓ Need to mix data types
- ✓ Want simple syntax
- ✓ Don't need key-value lookups
Dictionary Object
Scripting.Dictionary provides key-value pairs with fast lookups and advanced features.
Setup Required: Tools → References → Check "Microsoft Scripting Runtime"
Basic Dictionary Usage:
Count Unique Values:
Loop Through Dictionary:
Best Practices
Choosing the Right Structure
| Feature | Array | Collection | Dictionary |
|---|---|---|---|
| Fixed Size | Yes (Static) | No | No |
| Mixed Types | Variant only | Yes | Yes |
| Key Access | No | Optional | Yes |
| Performance | Fastest | Medium | Fast lookups |
| Add/Remove | Hard | Easy | Easy |
| Use When | Fixed data, speed critical | Simple lists, dynamic | Key-value pairs, lookups |