To add an array to a Dictionary in VBA, you either store the entire array as a single item under one key, or loop through the array and add each element as a separate item with its own key. The method you choose depends on whether you need to retrieve the whole array at once or access individual elements by key.
What a Dictionary Is and Why You’d Use It
The Scripting.Dictionary object (from Microsoft Scripting Runtime) is a key-value store available in VBA. Unlike a Collection, it lets you check if a key exists, change a value, and access items by key very quickly. A common use case is building a lookup table from a range or an array, then using that table to map one set of values to another (e.g., product codes to product names).
Arrays in VBA are fixed or dynamic lists of values. Combining them with a Dictionary is useful when you have a list of related data that you want to organize by a unique identifier. For example, you might have an array of employee names and want to store them under department keys.
Method 1: Storing the Whole Array as One Item
If you want the Dictionary to hold the entire array under a single key, you simply assign the array to the item. This is the simplest approach and is ideal when you need to retrieve the whole set later.
Sub StoreWholeArray()
' Requires: Tools > References > Microsoft Scripting Runtime
Dim dict As New Scripting.Dictionary
Dim arr(1 To 3) As String
arr(1) = "Red"
arr(2) = "Green"
arr(3) = "Blue"
' Add the array as a single item under key "Colors"
dict.Add "Colors", arr
' Retrieve it later
Dim retrieved As Variant
retrieved = dict("Colors")
MsgBox retrieved(1) ' Shows "Red"
End Sub
Note that the array is stored by reference, not by copy. If you modify the original array after adding it, the dictionary item will reflect those changes because both point to the same memory. If you need a snapshot, use ArrayCopy or assign to a new array first.
Method 2: Looping Through the Array and Adding Each Element
More commonly, you want each array element to be a separate item in the Dictionary, keyed by something meaningful. This is useful for building a lookup where the array elements are values and you derive keys from them or from a parallel array.
Sub AddEachElement()
Dim dict As New Scripting.Dictionary
Dim keys As Variant
Dim vals As Variant
Dim i As Long
keys = Array("A", "B", "C")
vals = Array(10, 20, 30)
For i = LBound(keys) To UBound(keys)
' Add each pair, but skip if key already exists
If Not dict.Exists(keys(i)) Then
dict.Add keys(i), vals(i)
End If
Next i
MsgBox dict("B") ' Shows 20
End Sub
If you have a single array and want to use its values as keys (with a default value), you can loop and add each element with a placeholder value like True.
Key Differences and How to Choose
- Whole array as item – Use when you need to retrieve the entire set later, or when the array is a logical unit (e.g., a list of coordinates for one point).
- Each element as separate item – Use when you need fast lookup by a unique key, or when you want to check if a value exists in the array using
dict.Exists. - Memory and performance – Storing a large array as a single item is faster to add, but looping through a large array to add each element is O(n) and may be slower. However, the lookup speed afterwards is O(1) for each key.
Common Problems and How to Avoid Them
“Key already exists” error – The most frequent issue. If you try to add a key that already exists, VBA throws a runtime error. Always check with dict.Exists(key) before adding, or use dict(key) = value which overwrites silently.
Forgetting to reference the Scripting Runtime – The Dictionary object is not part of the default VBA library. Go to Tools > References in the VBA editor and check “Microsoft Scripting Runtime”. Without it, you’ll get a “User-defined type not defined” error.
Array base mismatch – If you use Array() function, it creates a zero-based array. If you declare Dim arr(1 To 5), it’s one-based. Use LBound and UBound in loops to avoid off-by-one errors.
Alternative: Using a Collection or a Custom Class
VBA’s Collection object is simpler but lacks an Exists method, forcing you to loop through all items to check for a key. A Dictionary is generally faster for lookups. If you need more complex behavior (like storing multiple arrays or objects per key), you can create a custom class with properties and store instances of that class in the Dictionary.
Another alternative is to use a two-dimensional array or a ArrayList (from .NET) if you need dynamic resizing and sorting, but those are not native VBA and require additional references.
Working with Arrays from Excel Ranges
Often you’ll want to add a range of cells to a Dictionary. The quickest way is to read the range into a variant array, then loop through it. Note that a multi-column range produces a 2D array (1-based).
Sub AddRangeToDict()
Dim dict As New Scripting.Dictionary
Dim rng As Range
Dim data As Variant
Dim i As Long
' Assume data in A1:B10, keys in column A, values in column B
Set rng = ThisWorkbook.Sheets("Sheet1").Range("A1:B10")
data = rng.Value ' 2D array, 1-based
For i = 1 To UBound(data, 1)
If Not dict.Exists(data(i, 1)) Then
dict.Add data(i, 1), data(i, 2)
End If
Next i
End Sub
This is a common pattern for building lookup tables from worksheet data.
Frequently Asked Questions
Can I store an array as a value and later modify it? Yes, but remember it’s stored by reference. If you retrieve it and modify the array variable, the dictionary item changes. To avoid that, copy the array before storing or before modifying.
How do I add multiple arrays to a dictionary? You can store each array under a different key, or store an array of arrays (a jagged array) as a single item. For example, dict.Add "Group1", arr1 and dict.Add "Group2", arr2.
What’s the difference between Add and Item assignment? Add throws an error if the key exists. Using dict(key) = value either adds a new key or overwrites the existing value. Use Add when you want to enforce uniqueness, and assignment when you want to update.
Can I use a Dictionary without adding the reference? No, you must add the reference to Microsoft Scripting Runtime. Alternatively, you can use late binding with CreateObject("Scripting.Dictionary"), which avoids the reference but gives you less IntelliSense.
Is there a limit to the number of items in a Dictionary? The Dictionary is limited by available memory, not a fixed count. In practice, you can store hundreds of thousands of items, but performance may degrade if you exceed a few hundred thousand due to memory and hash collisions.
How do I remove an array from a dictionary? Use dict.Remove key to remove a specific item, or dict.RemoveAll to clear the entire dictionary. Remember that removing an item does not delete the array itself; it just removes the reference.
Related
- How to Do Data Entry in a Laptop: Step-by-Step
- Filtering for Duplicates in Excel: 4 Fast Ways
- JavaScript Random Number in Range: Simple Guide
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- VBA MsgBox Multiple Buttons: Options and ExamplesYes. In VBA, use the buttons argument of MsgBox to show a built-in group such as Yes/No or…
- Excel VBA: Copy a Worksheet to Another Workbook SafelyTo copy a worksheet from one open workbook to another in Excel VBA, use the worksheet’s Copy method…
- VBA Sort Worksheets Alphabetically: Code and SetupYes. In Excel for Microsoft 365 on Windows, VBA can sort a workbook’s worksheet tabs alphabetically; the macro…
- Excel VBA For Loop: Skip to the Next IterationExcel VBA does not have a built-in Continue For statement. To skip the rest of the current iteration…
- Active Range in VBA: What It Means and How to Use ItIn Excel VBA, “active range” usually means the cell or cells currently selected, but ActiveRange is not a…
- Excel Macro to Merge Cells: VBA Steps and LimitsYes. In Excel for Microsoft 365 on Windows, a VBA macro can merge the currently selected cells with…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.