VBA course · Lesson 28 of 33
Collections and dictionaries in VBA
Store items by key with Collection and Scripting.Dictionary: total sales per customer, find unique values, check if a key exists and handle Mac.
Arrays (Arrays in VBA: static, dynamic and fast range processing) are perfect when you know how many items you have and you find them by position: item 1, item 2, item 3. Real data rarely works like that. You want "the total for customer Acme Ltd", "has this invoice number been seen before?", "the list of distinct regions". For those questions VBA offers two containers that find items by a key instead of a number: the built-in Collection and the Dictionary from the Microsoft Scripting Runtime.
In this lesson you learn both, see when to pick which, and build three practical tools: a total per customer, a list of unique values and a duplicate checker.
The Collection object
A Collection is built into VBA, so it works everywhere, including Excel for Mac. Think of it as a list that grows as you add to it. You can add items with or without a key, read them by position or by key, remove them and count them.
Option Explicit
Sub CollectionBasics()
Dim staff As Collection
Set staff = New Collection
' Add item, key
staff.Add "Ana Silva", "E101"
staff.Add "Ben Okafor", "E102"
staff.Add "Chen Wei", "E103"
Debug.Print staff.Count ' 3
Debug.Print staff(1) ' Ana Silva (by position, starts at 1)
Debug.Print staff("E102") ' Ben Okafor (by key)
staff.Remove "E101" ' remove by key
Debug.Print staff.Count ' 2
Debug.Print staff(1) ' Ben Okafor: positions shift up
' Loop through every item
Dim person As Variant
For Each person In staff
Debug.Print person
Next person
End SubA few rules worth remembering:
- Positions start at 1, not 0.
- Keys must be text and are not case-sensitive:
"e102"finds the same item as"E102". - A key can be used only once. Adding a second item with the same key raises error 457 ("This key is already associated with an element of this collection").
- Asking for a key that does not exist raises error 5 ("Invalid procedure call or argument").
- You cannot read the list of keys back, and you cannot change an item in place. To "update" a number you remove it and add it again.
For Eachover a Collection is fast; readingcol(i)by position inside aFor i = 1 To col.Countloop gets slow for large collections, because the Collection walks from the start every time.
Checking whether a key exists
The Collection has no Exists method. The usual trick is a small helper that tries to read the key and catches the error (Error handling and debugging in VBA).
Option Explicit
Function KeyExists(ByVal col As Collection, ByVal key As String) As Boolean
Dim tmp As Variant
On Error Resume Next
' IsObject handles collections of objects as well as plain values
If IsObject(col(key)) Then
Set tmp = col(key)
Else
tmp = col(key)
End If
KeyExists = (Err.Number = 0)
On Error GoTo 0
End Function
Sub TestKeyExists()
Dim c As New Collection
c.Add 125.5, "INV-1001"
Debug.Print KeyExists(c, "INV-1001") ' True
Debug.Print KeyExists(c, "INV-9999") ' False
End SubUsing the duplicate-key error on purpose: unique values
Because a Collection refuses a second item with the same key, you can use it to build a list of distinct values: add every value with itself as the key and simply ignore the error for duplicates. This works on Windows and Mac.
Option Explicit
Sub UniqueRegionsWithCollection()
Dim ws As Worksheet
Dim regions As New Collection
Dim lastRow As Long
Dim r As Long
Dim reg As Variant
Dim outRow As Long
Set ws = ThisWorkbook.Worksheets("Sales")
lastRow = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row
On Error Resume Next ' duplicates raise error 457: skip them
For r = 2 To lastRow
regions.Add ws.Cells(r, "B").Value, CStr(ws.Cells(r, "B").Value)
Next r
On Error GoTo 0 ' always switch error trapping back on
outRow = 2
ws.Range("G1").Value = "Regions"
For Each reg In regions
ws.Cells(outRow, "G").Value = reg
outRow = outRow + 1
Next reg
End SubCStr is needed because keys must be text; if column B held numbers, using them directly as keys would fail. Keep On Error Resume Next wrapped as tightly as possible around the lines that are expected to fail.
The Dictionary object
The Scripting.Dictionary is the more powerful sibling. It is part of the Microsoft Scripting Runtime, a Windows component that ships with every copy of Windows. Compared with a Collection it can:
- tell you whether a key exists with
.Exists(key); - give you all keys and all items as arrays with
.Keysand.Items; - change an item in place:
dict(key) = newValue; - use numbers, dates or text as keys;
- be case-sensitive or not, as you choose, with
.CompareMode.
The easiest way to create one is late binding with CreateObject, which needs no reference. If you prefer IntelliSense (the member list that pops up as you type), set a reference under Tools > References > Microsoft Scripting Runtime and declare Dim d As Scripting.Dictionary / Set d = New Scripting.Dictionary instead. Binding is explained in Control Outlook, Word and PowerPoint from Excel VBA.
Option Explicit
Sub DictionaryBasics()
Dim prices As Object
Set prices = CreateObject("Scripting.Dictionary")
prices.CompareMode = vbTextCompare ' "keyboard" = "Keyboard"; set before adding items
prices.Add "Keyboard", 25
prices("Mouse") = 12 ' assigning to a new key adds it
prices("Monitor") = 190
Debug.Print prices.Count ' 3
Debug.Print prices("keyboard") ' 25 (text compare)
Debug.Print prices.Exists("Webcam") ' False
prices("Mouse") = 14 ' update in place
Dim k As Variant
For Each k In prices.Keys
Debug.Print k, prices(k)
Next k
prices.Remove "Monitor"
prices.RemoveAll ' empty it completely
End Subx = prices("Webcam"), does not raise an error in a Dictionary. It silently adds the key with an empty value. This can create ghost entries. Use .Exists before reading when you are not sure the key is there.CompareMode must be set while the dictionary is still empty. vbBinaryCompare (the default) treats "ACME" and "Acme" as different keys; vbTextCompare treats them as the same, which is usually what you want for names typed by people.
Example: total sales per customer
This is the job dictionaries were made for. The Sales sheet has one row per invoice; we want one line per customer with the total, in a single pass through the data.
| A | B | C | |
|---|---|---|---|
| 1 | Invoice | Customer | Amount |
| 2 | INV-1001 | Acme Ltd | 1200 |
| 3 | INV-1002 | Brightway | 450 |
| 4 | INV-1003 | Acme Ltd | 300 |
| 5 | INV-1004 | Coastline Foods | 980 |
| 6 | INV-1005 | Brightway | 150 |
Before: the Sales sheet
Option Explicit
Sub TotalsPerCustomer()
Dim ws As Worksheet
Dim totals As Object
Dim data As Variant
Dim r As Long
Dim cust As String
Dim out() As Variant
Dim i As Long
Dim k As Variant
Set ws = ThisWorkbook.Worksheets("Sales")
Set totals = CreateObject("Scripting.Dictionary")
totals.CompareMode = vbTextCompare
' Read the whole table into an array: much faster than cell by cell
data = ws.Range("A2:C" & ws.Cells(ws.Rows.Count, "A").End(xlUp).Row).Value
For r = 1 To UBound(data, 1)
cust = Trim$(CStr(data(r, 2)))
If cust <> "" Then
' If the key is new, totals(cust) starts as Empty, which counts as 0
totals(cust) = totals(cust) + data(r, 3)
End If
Next r
If totals.Count = 0 Then Exit Sub ' no data: nothing to write
' Build a 2-column output array and write it in one go
ReDim out(1 To totals.Count, 1 To 2)
i = 0
For Each k In totals.Keys
i = i + 1
out(i, 1) = k
out(i, 2) = totals(k)
Next k
ws.Range("E1:F1").Value = Array("Customer", "Total")
ws.Range("E2").Resize(totals.Count, 2).Value = out
End SubThe key line is totals(cust) = totals(cust) + data(r, 3). The first time a customer appears, reading totals(cust) adds the key with an empty value, and Empty + 1200 is 1200. Here the silent-add behaviour from the warning above is exactly what we want. Keys keep the order in which they were first added, so customers appear in order of their first invoice.
| E | F | |
|---|---|---|
| 1 | Customer | Total |
| 2 | Acme Ltd | 1500 |
| 3 | Brightway | 600 |
| 4 | Coastline Foods | 980 |
After: the summary in E1:F4
You could get the same numbers with SUMIFS or a PivotTable (Pivot tables with VBA: create, filter and refresh). The dictionary version shines when the logic is more involved, for example when you also need to count invoices, keep the latest date and skip cancelled rows in the same pass.
Storing several values per key
An item can be anything: a number, a string, an array, even another dictionary or an object of your own class (Class modules: build your own objects in VBA). A common pattern is to store an array of counters. Because you cannot change one element of an array stored in a dictionary directly, you take it out, change it and put it back.
Option Explicit
Sub CountAndSumPerCustomer()
Dim d As Object
Dim data As Variant
Dim r As Long
Dim stats As Variant
Dim k As Variant
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Sales")
Set d = CreateObject("Scripting.Dictionary")
data = ws.Range("A2:C6").Value
For r = 1 To UBound(data, 1)
If d.Exists(data(r, 2)) Then
stats = d(data(r, 2)) ' take a copy out
Else
stats = Array(0, 0#) ' (count, total)
End If
stats(0) = stats(0) + 1
stats(1) = stats(1) + data(r, 3)
d(data(r, 2)) = stats ' put it back
Next r
For Each k In d.Keys
stats = d(k) ' copy the array out to read it
Debug.Print k; ": "; stats(0); " invoices, total "; stats(1)
Next k
End SubExample: find duplicate invoice numbers
Option Explicit
Sub HighlightDuplicateInvoices()
Dim ws As Worksheet
Dim seen As Object
Dim r As Long
Dim lastRow As Long
Dim key As String
Dim dupCount As Long
Set ws = ThisWorkbook.Worksheets("Sales")
Set seen = CreateObject("Scripting.Dictionary")
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
ws.Range("A2:A" & lastRow).Interior.Pattern = xlNone
For r = 2 To lastRow
key = UCase$(Trim$(CStr(ws.Cells(r, "A").Value)))
If seen.Exists(key) Then
' Colour this row and the first occurrence
ws.Cells(r, "A").Interior.Color = RGB(255, 199, 206)
ws.Cells(seen(key), "A").Interior.Color = RGB(255, 199, 206)
dupCount = dupCount + 1
Else
seen.Add key, r ' remember the row of the first occurrence
End If
Next r
MsgBox dupCount & " duplicate row(s) found.", vbInformation
End SubHere the item stored for each key is the row number of its first appearance, so the macro can colour both rows.
Collection or Dictionary?
| Need | Collection | Dictionary |
|---|---|---|
| Works on Mac | Yes | No |
| Check if a key exists | Only with an error trick | .Exists |
| List all keys | No | .Keys |
| Change an item in place | No, remove and re-add | Yes |
| Case-sensitive keys | Never | Optional (CompareMode) |
| Key types | Text only | Text, numbers, dates |
| Order of items | Order added | Order added |
A sensible rule: use a Dictionary for lookups, counting and grouping when the workbook will only run on Windows. Use a Collection for simple lists of objects (for example a list of clsInvoice objects) and whenever the code must run on a Mac.
Mac fallback
CreateObject("Scripting.Dictionary") fails on a Mac with error 429. If you need key lookups there, use a Collection with the KeyExists helper, or store values in two parallel arrays. Free open-source "Dictionary" class modules that copy the Scripting.Dictionary interface also exist; if you use one, read its code before adding it to your project.
Common mistakes
- Using a number as a Collection key:
col.Add x, 5fails. Convert withCStr. - Reading a missing Dictionary key and creating an empty entry by accident.
- Setting
CompareModeafter items were added, which raises an error. - Leaving
On Error Resume Nextactive after the unique-values loop, which hides every later error. - Trying
d(key)(0) = 5to change an array inside a dictionary. It does not update the stored array (and with late binding it even raises an error). Copy the array out, change it, and assign it back.
Check yourself
1. What happens when you add a second item to a Collection with a key that is already used?
Collections refuse duplicate keys with error 457. That behaviour is what makes the unique-values trick work.
2. Which line safely checks a Dictionary for a key before reading it?
Reading d(key) for a missing key silently adds it. Exists checks without changing the dictionary.
3. Why is the Collection a better choice than the Dictionary in a workbook used on Windows and Mac?
The Collection is built into VBA itself, so it works on both systems.
4. In totals(cust) = totals(cust) + amount, what is totals(cust) the first time a customer appears?
Reading a missing key adds it with an Empty value, and Empty plus a number is that number.
5. When must CompareMode be set?
Changing CompareMode on a dictionary that already contains items raises an error.