In VBA, a dictionary (the Scripting.Dictionary object) lets you store key-value pairs — like a lookup table where each unique key maps to a value. This is far faster than searching a range or array for a match, especially with thousands of rows. You can use it to count occurrences, remove duplicates, or build custom mappings. This guide shows you how to create, fill, read, and manage a dictionary in Microsoft Excel VBA (Microsoft 365 on Windows; Mac steps noted where different).
What You’ll Need
- Microsoft Excel (any recent version; the VBA editor is the same).
- Access to the VBA editor: press Alt+F11 (Windows) or Fn+Option+F11 (Mac).
- The Microsoft Scripting Runtime library reference (optional but recommended for early binding).
Step-by-Step
- Open the VBA editor – In Excel, press Alt+F11 (Windows) or Fn+Option+F11 (Mac). In the Project Explorer, right-click any workbook object (e.g., VBAProject (Book1)) and choose Insert > Module to add a new module.
- Add the reference (recommended) – In the VBA editor, go to Tools > References…, scroll down to Microsoft Scripting Runtime, tick the checkbox, and click OK. This allows you to declare a dictionary as
Scripting.Dictionarydirectly (early binding). If you skip this, you can still useCreateObject("Scripting.Dictionary")(late binding) — no reference needed. - Declare and instantiate the dictionary – In your module, write a subroutine. Declare a variable of type
Scripting.Dictionaryand set it to a new instance. For early binding:Dim dict As Scripting.Dictionary Set dict = New Scripting.DictionaryFor late binding (no reference):
Dim dict As Object Set dict = CreateObject("Scripting.Dictionary") - Add items to the dictionary – Use the
.Addmethod with a unique key and a value. Keys must be unique; adding a duplicate key will raise an error. Example:dict.Add "Apple", 5 dict.Add "Banana", 3 dict.Add "Cherry", 8 - Check if a key exists – Use the
.Existsmethod before adding to avoid errors, or to conditionally update a value:If dict.Exists("Apple") Then MsgBox "Apple is in the dictionary" End If - Read a value by key – Use the key as an index. If the key doesn’t exist, you’ll get a runtime error. Example:
Dim qty As Integer qty = dict("Apple") ' returns 5 - Update an existing key’s value – Simply assign a new value to the key. This works only if the key already exists:
dict("Apple") = 10 - Loop through all keys and values – Use a
For Eachloop over.Keysand.Items. Example:Dim k As Variant For Each k In dict.Keys Debug.Print k & ": " & dict(k) Next k - Remove items – Use
.Removefor a single key, or.RemoveAllto clear everything:dict.Remove "Banana" ' removes Banana dict.RemoveAll ' empties the dictionary - Get the count – Use the
.Countproperty:MsgBox dict.Count - Sort or manipulate keys/values – Dictionaries do not have a built-in sort. To sort, copy keys to an array, sort the array, then loop. Example:
Dim arrKeys As Variant arrKeys = dict.Keys ' Use a simple bubble sort or Excel's Sort via Application.Transpose ' Then iterate over arrKeys in order. - Use a dictionary to count occurrences – A common pattern: loop through a range and increment counts. Example with a range A1:A10:
Dim cell As Range Dim dictCount As Scripting.Dictionary Set dictCount = New Scripting.Dictionary For Each cell In Range("A1:A10") If cell.Value <> "" Then If dictCount.Exists(cell.Value) Then dictCount(cell.Value) = dictCount(cell.Value) + 1 Else dictCount.Add cell.Value, 1 End If End If Next cell - Clean up – When done, set the dictionary object to
Nothingto free memory (especially in long-running macros):Set dict = Nothing
Common Mistakes
- Adding a duplicate key – Causes runtime error 457. Always check
Existsbefore adding. - Forgetting to set the reference – If you declare as
Scripting.Dictionarywithout the reference, you’ll get a compile error. Use late binding or add the reference. - Using
.Addon an existing key – Same as duplicate key error. - Assuming keys are case-insensitive – By default, dictionary keys are case-sensitive. To make them case-insensitive, set
dict.CompareMode = vbTextComparebefore adding items. - Not clearing the dictionary between runs – If you reuse a dictionary variable, it retains old data. Use
.RemoveAllor set toNothing. - Using
dict(key)when key doesn’t exist – This adds the key with an empty value (default behavior) and can cause subtle bugs. Always checkExistsfirst for reading.
Tips
- Use early binding when possible – It gives you IntelliSense and better performance. Late binding is fine for portability.
- Set
CompareModeearly – If you want case-insensitive keys, set it immediately after creating the dictionary, before adding any items. - Use dictionaries for de-duplication – Add each item’s key to the dictionary; if it doesn’t exist, it’s unique.
- Combine with arrays for speed – Reading/writing to a dictionary is faster than looping through worksheet cells. Load your data into an array first, then process.
- Use
.Itemsto get all values at once – You can assigndict.Itemsto a variant array and write it directly to a range withRange.Value = Application.Transpose(arr). - Always save a copy of your workbook before running a macro – Macros cannot be undone with Ctrl+Z, so test on a backup file.
Troubleshooting
- Compile error: “User-defined type not defined” – This means you used
Scripting.Dictionarywithout adding the reference. Either add the reference (Tools > References) or switch to late binding withCreateObject. - Runtime error 457: “This key is already associated with an element” – You tried to add a duplicate key. Check
Existsbefore adding, or usedict(key) = valueto overwrite. - Runtime error 5: “Invalid procedure call or argument” – Often happens when you try to read a non-existent key. Always verify with
Exists. - Dictionary not retaining values between macro runs – Dictionaries are in-memory objects; they don’t persist after the macro ends. If you need persistence, write to a worksheet or a file.
- Keys are case-sensitive when you don’t want them to be – Set
CompareMode = vbTextComparebefore adding items. - Macro works on Windows but fails on Mac – The
Scripting.Dictionaryis available on Mac in recent Excel versions, but if you use late binding, ensure the ProgID is correct. On Mac, you may need to useCreateObject("Scripting.Dictionary")as well; it should work in Microsoft 365.
Frequently Asked Questions
- Can I use a dictionary in Excel VBA without adding a reference? – Yes, use
CreateObject("Scripting.Dictionary")and declare the variable asObject. This is late binding and works without the reference. - How do I make dictionary keys case-insensitive? – Set the
CompareModeproperty tovbTextCompareimmediately after creating the dictionary, before adding any items. - What is the maximum number of items a dictionary can hold? – Theoretically limited by memory, but practically you can store hundreds of thousands of items. Performance remains good, but for millions of records, consider using a Collection or an array.
- Can I store arrays or objects as dictionary values? – Yes, values can be any data type, including arrays, objects, or even other dictionaries. Just assign them appropriately.
- How do I sort a dictionary by key or value? – Dictionaries are not sortable. Copy the keys (or items) to an array, sort the array using a sorting algorithm or Excel’s worksheet sort, then iterate through the sorted array to access the dictionary.
- Is a dictionary faster than using
Application.MatchorFind? – For repeated lookups on a large dataset, a dictionary is usually faster because it uses hashing for O(1) average lookup, whileMatchandFindare O(n) or worse. For a one-off lookup,Matchmay be simpler.
Related
- Windows Display Shortcut Keys: Full List
- JavaScript Random Number: How to Generate One
- How to Do Data Entry in a Laptop: Step-by-Step
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- Excel VBA Function Parameters: Defaults, ByRef, and MoreIn Excel VBA, a standard function parameter is a named input declared in the function’s parentheses, such as…
- VBA Split Function: How to Break Text into an ArrayIn VBA, use the Split function to divide a string wherever a specified delimiter appears; it returns the…
- How to Use Macros in SteelSeries GGTo use a macro in SteelSeries GG, open Engine, select a compatible device, create or record a macro…
- VBA Sort Column Ascending in ExcelTo sort a column in ascending order with VBA, use Excel’s Range.Sort method and set Order1:=xlAscending. For example,…
- 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…
- Excel UserForm Keeps Changing Size? Causes and FixesAn Excel UserForm usually changes size because VBA or its AutoSize setting changes its dimensions, or because Windows…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.