Tabellab

Why You Need Keyed Storage

Lesson 1 of 7Reading

The problem arrays cannot solve neatly

An array is brilliant when you know where something is: row 412, column 3. It is hopeless when the question is have I seen customer 88431 before? Answering that means walking through everything collected so far โ€” a loop inside a loop, whose cost grows with the square of the row count. Ten times the data, a hundred times the work.

What a nested search really costs

This finds unique values the slow way. With 10,000 rows it makes roughly fifty million comparisons, and it is what almost everyone writes first:

Sub UniqueTheSlowWay()
    Dim data As Variant
    Dim seen() As String
    Dim r As Long, i As Long, n As Long
    Dim found As Boolean

    data = Range("A2:A10001").Value
    ReDim seen(1 To UBound(data, 1))

    For r = 1 To UBound(data, 1)
        found = False
        For i = 1 To n
            If seen(i) = CStr(data(r, 1)) Then
                found = True
                Exit For
            End If
        Next i
        If Not found Then
            n = n + 1
            seen(n) = CStr(data(r, 1))
        End If
    Next r

    Debug.Print n & " unique values"
End Sub

A keyed store answers instantly

A Dictionary stores things under a key you choose, and a lookup costs the same tiny amount of time whether it holds ten entries or a million. The inner loop disappears.

A duplicate checker you can use today

Here is that idea as something finished. Paste it into a normal module and run ListDuplicates. It creates a small Key Demo sheet if you have none, reads column A, and writes a Duplicate Report listing every value that appears more than once, how often, and on which rows. Point it at a real customer or article list and it does in a second what an eye-and-highlighter pass does in an hour.

Option Explicit

Sub ListDuplicates()
    Dim ws As Worksheet
    Dim report As Worksheet
    Dim counts As Object
    Dim rowsFor As Object
    Dim data As Variant
    Dim lastRow As Long
    Dim r As Long
    Dim k As Variant
    Dim key As String
    Dim outRow As Long

    Set ws = DemoSheet()
    lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
    If lastRow < 2 Then Exit Sub

    data = ws.Range("A2:A" & lastRow).Value

    Set counts = CreateObject("Scripting.Dictionary")
    Set rowsFor = CreateObject("Scripting.Dictionary")
    counts.CompareMode = vbTextCompare
    rowsFor.CompareMode = vbTextCompare

    For r = 1 To UBound(data, 1)
        key = Trim$(CStr(data(r, 1)))
        If Len(key) > 0 Then
            counts(key) = counts(key) + 1
            If counts(key) = 1 Then
                rowsFor(key) = CStr(r + 1)
            Else
                rowsFor(key) = rowsFor(key) & ", " & (r + 1)
            End If
        End If
    Next r

    Set report = SheetNamed("Duplicate Report")
    report.Cells.Clear
    report.Range("A1:C1").Value = Array("Value", "Times", "Rows")
    report.Range("A1:C1").Font.Bold = True

    outRow = 1
    For Each k In counts.Keys
        If counts(k) > 1 Then
            outRow = outRow + 1
            report.Cells(outRow, 1).Value = k
            report.Cells(outRow, 2).Value = counts(k)
            report.Cells(outRow, 3).Value = rowsFor(k)
        End If
    Next k

    report.Columns("A:C").AutoFit
    report.Activate

    MsgBox (lastRow - 1) & " rows read." & vbCrLf & _
           counts.Count & " distinct values." & vbCrLf & _
           (outRow - 1) & " of them appear more than once.", _
           vbInformation, "Duplicate check"
End Sub

Private Function DemoSheet() As Worksheet
    Dim ws As Worksheet
    Dim names As Variant
    Dim i As Long

    Set ws = SheetNamed("Key Demo")
    If ws.Range("A1").Value <> "" Then
        Set DemoSheet = ws
        Exit Function
    End If

    ws.Range("A1").Value = "Customer"
    ws.Range("A1").Font.Bold = True

    ' Note the stray trailing space and the lower-case entry.
    names = Array("Meier AG", "Brunner", "Steiner GmbH", "Meier AG", _
                  "Keller", "brunner", "Steiner GmbH ", "Waber", _
                  "Meier AG", "Keller", "Zumbrunnen", "Steiner GmbH")

    For i = LBound(names) To UBound(names)
        ws.Cells(i + 2, 1).Value = names(i)
    Next i

    ws.Columns("A").AutoFit
    Set DemoSheet = ws
End Function

Private Function SheetNamed(ByVal sheetName As String) As Worksheet
    Dim ws As Worksheet
    Dim found As Worksheet

    For Each ws In ThisWorkbook.Worksheets
        If ws.Name = sheetName Then Set found = ws
    Next ws

    If found Is Nothing Then
        Set found = ThisWorkbook.Worksheets.Add
        found.Name = sheetName
    End If

    Set SheetNamed = found
End Function

Line by line

  • The whole column is read at once with data = ws.Range(โ€ฆ).Value, so the sheet is touched once rather than once per row.
  • counts(key) = counts(key) + 1 is the pattern to memorise. Reading a key that does not exist yet returns Empty, and Empty + 1 is 1, so nothing needs initialising. That behaviour also has a sharp edge, which lesson three covers.
  • The second dictionary, rowsFor, collects the row numbers under the same key โ€” r + 1 because the array starts at sheet row 2.
  • counts.Keys returns every key in the order it was first seen, so the report follows the data.
  • SheetNamed creates a sheet only if it is missing, so repeated runs do not leave you with Duplicate Report (2).
  • One pass does all of it. Add a zero to the row count and this takes ten times as long, not a hundred.

The trap: two keys that look identical

A key matches only if it is exactly the same. "Steiner GmbH " with a trailing space from a web export and "Steiner GmbH" typed by a colleague are two different keys โ€” so the report comes back empty while you stare at two obviously identical rows. Capitalisation does the same unless you say otherwise. The demo data contains both faults deliberately, which is why the macro trims every key and sets the compare mode first:

Set counts = CreateObject("Scripting.Dictionary")
counts.CompareMode = vbTextCompare       ' before the first key goes in
key = Trim$(CStr(data(r, 1)))            ' text, and no stray spaces
counts(key) = counts(key) + 1

The two tools in this course

  • Collection โ€” built into VBA, available everywhere including Excel for Mac, holds an ordered list with optional keys. Simple, and limited: it cannot tell you whether a key exists without an error handler.
  • Scripting.Dictionary โ€” a Windows-only component. It stores key and item pairs, can be asked whether a key exists, lists its keys, and lets you change an item in place. On macOS it does not exist, so a Collection has to stand in.
  • Rule of thumb โ€” for an ordered list, a Collection. To look things up, count or group them, a Dictionary.
Whenever you catch yourself writing a loop inside a loop to match one list against another, stop. That is nearly always a Dictionary in disguise.

How it goes on

The next lessons take both containers apart: what a Collection can and cannot do, the full Dictionary member list including the behaviour that silently corrupts counts, and late binding with CreateObject versus early binding with a reference. Then come the recipes โ€” counting and grouping rows in one pass, matching two lists against each other, and storing whole records behind a key instead of one number.

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.

Work needed to find unique values (worst case) 10M20M30M40M50M 0 02,5005,0007,50010,000 Rows in column A โ‰ˆ 50 million comparisons Dictionary: 10,000 lookups Nested loop Dictionary
Comparisons needed to find unique values, worst case where every value is different. The nested loop grows with the square of the row count; the Dictionary line hugs the axis because it needs about one lookup per row.

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.

Reading a missing key with the brackets does not just return Empty, it also adds that key to the Dictionary. Inside the counting line that is exactly what you want. In a simple check such as 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 rowsLab macro: Trim + vbTextCompareDefault Dictionary=COUNTIF($A$2:$A$13,A2)
Meier AG2, 5, 10333
Brunner3, 721 + 1 (two keys: "Brunner", "brunner")2
Steiner GmbH4, 8, 1332 + 1 (two keys, one with a trailing space)2
Keller6, 11222
Waber9111
Zumbrunnen12111
Distinct keys12 rows read68n/a
Names reported as duplicates43n/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.

counts(key) after one pass over the Key Demo sheet Meier AG3 ยท rows 2, 5, 10Brunner2 ยท rows 3, 7Steiner GmbH3 ยท rows 4, 8, 13Keller2 ยท rows 6, 11Waber1 ยท row 9Zumbrunnen1 ยท row 12 0123 in the Duplicate Report seen once, not reported
What the Dictionary holds after one pass over the lab data. Green keys have a count above 1 and land in the Duplicate Report, together with the rows collected in the second Dictionary, rowsFor.

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

  1. Save your workbook as .xlsm (File โ†’ Save As โ†’ Excel Macro-Enabled Workbook), otherwise the code is thrown away when you close it.
  2. Press Alt+F11 to open the Visual Basic Editor. On a Mac use Fn+Option+F11 or Tools โ†’ Macro โ†’ Visual Basic Editor, but note that Scripting.Dictionary exists only on Windows.
  3. Choose Insert โ†’ Module and paste the whole ListDuplicates listing from the lab, including the two private helper functions at the bottom.
  4. Put the cursor anywhere inside Sub ListDuplicates and press F5. The first run creates the Key Demo sheet with the twelve sample names, then writes the Duplicate Report.
  5. Press Ctrl+G to show the Immediate window. Type ?Trim$("Steiner GmbH ") = "Steiner GmbH" and press Enter to see True: this is the comparison the macro makes after trimming.
  6. To watch the counting happen, click in the code and press F8 repeatedly to step line by line. Hover over key or add counts to the Locals window (View โ†’ Locals Window) to see the count grow.
  7. To use your own list, paste it into column A of Key Demo with a header in A1, or change Set ws = DemoSheet() to Set ws = ThisWorkbook.Worksheets("Customers") with your sheet name.
  8. Run it again. Because SheetNamed reuses existing sheets and the report starts with report.Cells.Clear, repeated runs overwrite the old report instead of piling up copies.
Keep a copy of the raw export before you start cleaning. A duplicate report is only useful if somebody can go back to rows 4, 8 and 13 and see what was actually there.

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 = vbTextCompare
key = Trim$(CStr(data(r, 1)))
If Len(key) > 0 Then counts(key) = counts(key) + 1

  • CStr turns 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 = vbTextCompare makes "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) > 0 skips 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 0
End 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.

Illustration for the Tabellab course Collections and Dictionary in Excel VBA
Collections & Dictionary: group, count and de-duplicate thousands of rows in one pass.

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 with Trim$ and vbTextCompare before 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 .Add with a key that already exists. Either test with .Exists first or use the bracket assignment d(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 with d.Exists(key).
  • Numbers and text treated as different customers. The cell values have mixed types: 1001 and "1001". Wrap the key in CStr, or CLng if every key is truly numeric.
  • Run-time error 429, "ActiveX component can't create object". You are on a Mac, where Scripting.Dictionary does 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 touch ws.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 shortcutWhat it does
Set d = CreateObject("Scripting.Dictionary")Creates an empty Dictionary (late binding, no reference needed)
d.CompareMode = vbTextCompareKeys match regardless of case; set before the first key
d(key) = d(key) + 1Counts 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, itemAdds a pair; error 457 if the key already exists
d.Keys / d.ItemsArrays of all keys or items, in the order the keys were added
d.CountNumber of distinct keys
d.Remove key / d.RemoveAllDeletes one pair or all of them
Dim c As New Collection ยท c.Add item, keyBuilt-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+GOpen 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 a SUMIFS per 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 Exists returns 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 VLOOKUP on 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.

  1. The Collection Object
  2. Scripting.Dictionary Basics
  3. Early vs Late Binding
  4. Counting and Grouping Rows
  5. De-duplicating and Matching Lists
  6. Storing More Than a Number

Buy course โ€” โ‚ฌ9.90 See the full course

Knowledge check

Your duplicate report comes back empty although the same customer plainly appears twice in the column. What is the most likely cause?

Continues in this course
  • The Collection Object
  • Scripting.Dictionary Basics
  • Early vs Late Binding
  • Counting and Grouping Rows
  • De-duplicating and Matching Lists
  • Storing More Than a Number

Buy the course to unlock the remaining 6 lessons, the exam and the certificate.

Buy course โ€” โ‚ฌ9.90