Who this lesson is for
If you write VBA for real workbooks, sooner or later you are asked a question that sounds trivial: which customers appear twice in this export?, how many orders did each region place?, which article numbers on list A are missing from list B? The first macro almost everyone writes for this uses a loop inside a loop. It works on twenty rows, it is slow on two thousand, and on a full year of ERP data it turns Excel into a spinning wheel for minutes. This lesson is for the analyst, controller or office automator who has hit that wall, or wants to avoid it, and it explains the one idea that removes it: storing things under a key.
The free lab above gives you a finished duplicate checker called ListDuplicates. Below we take the same twelve customer names it creates on its Key Demo sheet and walk through what happens inside, why the result is right, and what would make it wrong. By the end you will know when to reach for a Dictionary, when a Collection is enough, and how to recognise the two invisible faults that make identical-looking values disagree.
Arrays answer "where", keys answer "have I seen it"
An array is a numbered row of boxes. If you know the box number, getting at the content is instant: data(412, 3). But most business questions are not about positions. They are about identity: is this customer number already in my list? To answer that with an array you must look in every box you have filled so far. That is the inner loop in UniqueTheSlowWay, and it is the reason the macro slows down so badly.
Count the work. With 10,000 rows that are all different, row 2 is compared with one earlier value, row 3 with two, row 10,001 with 9,999. Added up that is roughly 10,000 ร 10,000 รท 2, about fifty million comparisons. Double the rows and the comparisons quadruple. This is what programmers call quadratic growth, and it is why a macro that felt fine in testing becomes unusable on production data.
A keyed store works differently. When you put a value in, it calculates a short fingerprint of the key (a hash) and files the entry under that fingerprint. When you ask for the key again, it calculates the same fingerprint and goes straight to the right place. The cost of one lookup stays roughly the same whether the store holds ten keys or a million, so 10,000 rows need roughly 10,000 lookups. The chart below shows the difference on the same scale.
You do not need to understand hashing to use it. You only need the mental model: a Dictionary is a two-column table of keys and items, with an index on the key column that makes lookups instant. In VBA you get one with CreateObject("Scripting.Dictionary"), and the course also covers the built-in Collection, which is a simpler cousin.
The pattern you will use most: counting by key
Nearly every grouping macro in this course comes down to one line:
counts(key) = counts(key) + 1
It reads like a sentence: take whatever is stored under this key, add one, store it back. The clever part is what happens the first time a key appears. Reading counts(key) for a key that does not exist yet returns Empty, and VBA treats Empty + 1 as 1. So there is no "if it is new, start at zero" branch. The same trick sums amounts instead of counting rows: totals(region) = totals(region) + amount.
If counts(key) > 1 Then on an unknown key it quietly creates entries you never meant to store. When you only want to ask, use counts.Exists(key). Lesson three takes this apart in detail.Worked example: twelve customers, six real names
The lab macro fills column A of the Key Demo sheet with twelve customer names, starting in row 2. Two of them are deliberately dirty, the way real exports are: "brunner" in row 7 is typed in lower case, and "Steiner GmbH " in row 8 carries a trailing space you cannot see on screen. The table compares three ways of counting the same column. The first is the lab macro, which trims every value and sets CompareMode = vbTextCompare. The second is a Dictionary left on its default settings. The third is the worksheet formula =COUNTIF($A$2:$A$13,A2) entered next to the first occurrence of each name.
| Customer (first spelling seen) | Sheet rows | Lab macro: Trim + vbTextCompare | Default Dictionary | =COUNTIF($A$2:$A$13,A2) |
|---|---|---|---|---|
| Meier AG | 2, 5, 10 | 3 | 3 | 3 |
| Brunner | 3, 7 | 2 | 1 + 1 (two keys: "Brunner", "brunner") | 2 |
| Steiner GmbH | 4, 8, 13 | 3 | 2 + 1 (two keys, one with a trailing space) | 2 |
| Keller | 6, 11 | 2 | 2 | 2 |
| Waber | 9 | 1 | 1 | 1 |
| Zumbrunnen | 12 | 1 | 1 | 1 |
| Distinct keys | 12 rows read | 6 | 8 | n/a |
| Names reported as duplicates | 4 | 3 | n/a |
Three lessons hide in this small table. First, the lab macro gets it right: six real customers, four of which appear more than once, which is exactly what its message box reports. Second, a Dictionary on default settings compares keys character by character in binary mode, so a capital letter or a trailing space creates a separate key and the report understates the duplicates. Third, the worksheet is not a safe reference either: COUNTIF ignores case, so it catches Brunner, but it does not trim, so it still misses the third Steiner. If you want a worksheet cross-check that behaves like the macro, use =SUMPRODUCT(--(TRIM($A$2:$A$13)=TRIM(A2))), which trims both sides and compares without regard to case. In Excel 365, =ROWS(UNIQUE(TRIM(A2:A13))) returns the distinct count, 6.
The second Dictionary in the lab, rowsFor, uses the same keys but stores text instead of a number. The first time a key appears it stores the row number; after that it appends ", " and the next row. That is how the report can say Steiner GmbH, 3, rows 4, 8, 13 without searching anything afterwards. Two dictionaries side by side, sharing keys, is a perfectly normal design. Lesson seven shows a neater one, where each key holds a whole record.
How to run and adapt the lab macro, step by step
- Save your workbook as .xlsm (File โ Save As โ Excel Macro-Enabled Workbook), otherwise the code is thrown away when you close it.
- Press
Alt+F11to open the Visual Basic Editor. On a Mac useFn+Option+F11or Tools โ Macro โ Visual Basic Editor, but note thatScripting.Dictionaryexists only on Windows. - Choose Insert โ Module and paste the whole
ListDuplicateslisting from the lab, including the two private helper functions at the bottom. - Put the cursor anywhere inside
Sub ListDuplicatesand pressF5. The first run creates the Key Demo sheet with the twelve sample names, then writes the Duplicate Report. - Press
Ctrl+Gto show the Immediate window. Type?Trim$("Steiner GmbH ") = "Steiner GmbH"and press Enter to seeTrue: this is the comparison the macro makes after trimming. - To watch the counting happen, click in the code and press
F8repeatedly to step line by line. Hover overkeyor addcountsto the Locals window (View โ Locals Window) to see the count grow. - To use your own list, paste it into column A of Key Demo with a header in A1, or change
Set ws = DemoSheet()toSet ws = ThisWorkbook.Worksheets("Customers")with your sheet name. - Run it again. Because
SheetNamedreuses existing sheets and the report starts withreport.Cells.Clear, repeated runs overwrite the old report instead of piling up copies.
Why the two cleaning lines matter so much
Exact matching is the whole point of a key, and also its biggest trap. The Dictionary has no idea that "Steiner GmbH " and "Steiner GmbH" mean the same company. It sees two different strings and files them under two different fingerprints. That is why the lab macro makes every key presentable before it touches the store:
Set counts = CreateObject("Scripting.Dictionary")counts.CompareMode = vbTextComparekey = Trim$(CStr(data(r, 1)))If Len(key) > 0 Then counts(key) = counts(key) + 1
CStrturns whatever is in the cell into text. Without it, a customer number stored as the number 1001 in one row and as the text "1001" in another become two different keys, because a Dictionary key keeps its data type.Trim$removes leading and trailing spaces. The dollar sign makes it return a String rather than a Variant, a small and harmless speed habit.CompareMode = vbTextComparemakes "brunner" and "Brunner" the same key. It must be set while the Dictionary is still empty; changing it after the first key has gone in raises a run-time error.If Len(key) > 0skips blank cells, so empty rows at the bottom of an export do not show up as a duplicate called nothing.
Trim is not the end of the story. Data copied from web pages often contains a non-breaking space, character 160, which Trim$ does not remove. If two values still refuse to match, check them with Len or with AscW(Right$(value, 1)) in the Immediate window. The VBA Text & Strings course has a full lesson on cleaning such characters.
Collection or Dictionary?
VBA has two keyed containers and this course teaches both. The Collection is part of the VBA language itself, so it works everywhere, including Excel for Mac, without any reference or CreateObject. You add items with an optional key, read them by position or key, and loop over them with For Each. Its weakness is that it cannot tell you whether a key exists: you must try to read it and catch the error. Its keys also always compare without regard to case, and you cannot list the keys back out.
The Dictionary comes from the Windows Scripting Runtime. It has Exists, Keys, Items, Remove, a configurable CompareMode, and items you can overwrite in place. For counting, grouping, matching and de-duplicating it is the better tool. A compact rule: ordered list of things, Collection; anything you look up, Dictionary. When your code must also run on a Mac, a Collection with an error handler can stand in for Exists:
Function InCollection(col As Collection, ByVal key As String) As Boolean Dim tmp As Variant On Error Resume Next tmp = col(key) InCollection = (Err.Number = 0) On Error GoTo 0End Function
That helper works for collections holding plain values such as numbers or text. If the items are objects such as worksheets, the read needs Set instead, so keep a second version for that case. Lesson two also shows the "useful accident": adding every value with itself as the key, inside On Error Resume Next, leaves you with a list of unique values, because the duplicate adds simply fail.

Common mistakes and how to spot them
- The report is empty although you can see a duplicate. One copy has a trailing space, a non-breaking space or different capitalisation. Spot it with
?Len(Range("A8").Value)in the Immediate window: a length one higher than expected gives it away. Fix it withTrim$andvbTextComparebefore the first key goes in. - Run-time error 5 when setting CompareMode. You set it after adding keys. Move the line directly below
CreateObject. - Run-time error 457, "This key is already associated with an element of this collection". You used
.Addwith a key that already exists. Either test with.Existsfirst or use the bracket assignmentd(key) = value, which adds or overwrites. - Counts that are too high, or keys you never added. Somewhere you read
d(key)just to look, and the read created the key. Replace those reads withd.Exists(key). - Numbers and text treated as different customers. The cell values have mixed types: 1001 and "1001". Wrap the key in
CStr, orCLngif every key is truly numeric. - Run-time error 429, "ActiveX component can't create object". You are on a Mac, where
Scripting.Dictionarydoes not exist. Use a Collection there. - The macro is still slow. Check that you read the column into an array once (
data = ws.Range(...).Value) and do not touchws.Cells(r, 1)inside the loop; reading cells one by one is often slower than the counting itself.
Quick reference: members and shortcuts used in this lesson
| Code or shortcut | What it does |
|---|---|
Set d = CreateObject("Scripting.Dictionary") | Creates an empty Dictionary (late binding, no reference needed) |
d.CompareMode = vbTextCompare | Keys match regardless of case; set before the first key |
d(key) = d(key) + 1 | Counts by key; a missing key starts as Empty, which adds as 0 |
d.Exists(key) | True or False, without creating the key |
d.Add key, item | Adds a pair; error 457 if the key already exists |
d.Keys / d.Items | Arrays of all keys or items, in the order the keys were added |
d.Count | Number of distinct keys |
d.Remove key / d.RemoveAll | Deletes one pair or all of them |
Dim c As New Collection ยท c.Add item, key | Built-in ordered container with optional, case-insensitive keys |
=SUMPRODUCT(--(TRIM($A$2:$A$13)=TRIM(A2))) | Worksheet cross-check that trims and ignores case like the lab macro |
Alt+F11 ยท F5 ยท F8 ยท Ctrl+G | Open the editor ยท run ยท step one line ยท Immediate window |
Real-world uses
- Customer master clean-up. Before a CRM migration, list every customer name or VAT number that appears more than once, with the rows, so a person can decide which record survives.
- Sales by region or product in one pass. Read 50,000 order lines into an array, add each amount to
totals(region), and write a summary table in a fraction of the time aSUMIFSper row would take to recalculate. - Reconciling two lists. Load the article numbers from the warehouse count into a Dictionary, then loop over the ERP list and flag every number for which
Existsreturns False. What is left in the first Dictionary afterwards is missing from the ERP. - Invoice duplicate checks in accounts payable. Build a key from supplier number and invoice number, for example
key = supplier & "|" & invoiceNo, and stop the payment run if a key is already present. - Lookup tables for other macros. Load a price list or a cost-centre mapping into a Dictionary once at the start, then translate thousands of codes without a single
VLOOKUPon the sheet.
What you will build in the rest of this course
This first lesson is free. The remaining six lessons are part of the full course, available as a one-time purchase of $9.90, and each one ends with a macro you can run on your own data.
The Collection Object. Everything the built-in container can do: adding with and without keys, reading by position and by key, why For Each beats an index loop, and the duplicate-add trick that produces a unique list on any platform, including Excel for Mac, plus how to remove items safely by looping backwards.
Scripting.Dictionary Basics. Keys and items, Add versus the bracket shortcut, and the behaviour that surprises almost everyone: how simply reading a missing key creates it, and how that silently inflates counts in code that looks correct.
Early vs Late Binding. CreateObject versus a reference to Microsoft Scripting Runtime. You get IntelliSense and type checking with one, portability with the other, and a clear rule for which to ship to colleagues.
Counting and Grouping Rows. Counting in three lines, summing instead of counting, and writing the grouped result back to the sheet in one block, so a 50,000-row export becomes a tidy summary table in a second.
De-duplicating and Matching Lists. Unique values in one pass, finding the first row where each duplicate appears, and matching one list against another to see what is missing on either side, the job that usually takes a morning of VLOOKUP columns.
Storing More Than a Number. Items can be anything: arrays, Collections or other dictionaries. You will keep a whole record behind each key, group rows into lists per customer, and nest dictionaries for two-level summaries such as region by month.
Summary
Nested loops ask "have I seen this?" by searching everything, and their cost grows with the square of the data. A Dictionary answers the same question with one lookup, so a single pass is enough to count, group or de-duplicate any column. The pattern to remember is counts(key) = counts(key) + 1, preceded by CompareMode = vbTextCompare and a trimmed, text-converted key, because keys only match when they are exactly identical. Now scroll back up to the lab, run ListDuplicates, and check that it reports six distinct customers and four duplicates. Then point it at a real list from your own work and see what turns up.
Frequently asked questions
What is the difference between a Collection and a Dictionary in VBA?
A Collection is built into VBA and works on Windows and Mac, but it cannot list its keys or tell you whether a key exists without an error handler. A Scripting.Dictionary is Windows-only and offers Exists, Keys, Items, Remove and a configurable CompareMode, which makes it better for lookups and counting.
How do I find duplicates in a column with VBA?
Read the column into an array, loop over it once and count each trimmed value with counts(key) = counts(key) + 1 in a Dictionary set to vbTextCompare. Every key whose count is above 1 is a duplicate.
Why does my Dictionary not find a key that is clearly there?
Keys must match exactly. A trailing space, a non-breaking space, different capitalisation or a number stored as text instead of a number all create a different key. Trim and convert the key with CStr, and set CompareMode to vbTextCompare before adding anything.
Does Scripting.Dictionary work on Excel for Mac?
No. It belongs to the Windows Scripting Runtime, so CreateObject("Scripting.Dictionary") fails on macOS with error 429. Use a VBA Collection, or a Dictionary replacement class, when your code has to run on a Mac.
Is a Dictionary faster than a nested loop in VBA?
For matching and de-duplicating, yes, and the gap grows with the data. A nested loop over 10,000 unique values makes about 50 million comparisons, while a Dictionary needs roughly one lookup per row.
How do I check if a key exists in a VBA Dictionary?
Use d.Exists(key), which returns True or False and does not change the Dictionary. Avoid testing with d(key) on its own, because reading a missing key with the brackets adds that key with an Empty item.
Keep going: Collections & Dictionary
This free lab is lesson 1 of 7. Unlock the other 6 hands-on labs, the final exam and your certificate for a one-time โฌ9.90.
- The Collection Object
- Scripting.Dictionary Basics
- Early vs Late Binding
- Counting and Grouping Rows
- De-duplicating and Matching Lists
- Storing More Than a Number