How to Make a Dictionary in VBA

VBA & macros · Updated November 23, 2026

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

  1. 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.
  2. 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.Dictionary directly (early binding). If you skip this, you can still use CreateObject("Scripting.Dictionary") (late binding) — no reference needed.
  3. Declare and instantiate the dictionary – In your module, write a subroutine. Declare a variable of type Scripting.Dictionary and set it to a new instance. For early binding:
    Dim dict As Scripting.Dictionary
    Set dict = New Scripting.Dictionary

    For late binding (no reference):

    Dim dict As Object
    Set dict = CreateObject("Scripting.Dictionary")
  4. Add items to the dictionary – Use the .Add method 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
  5. Check if a key exists – Use the .Exists method before adding to avoid errors, or to conditionally update a value:
    If dict.Exists("Apple") Then
        MsgBox "Apple is in the dictionary"
    End If
  6. 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
  7. 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
  8. Loop through all keys and values – Use a For Each loop over .Keys and .Items. Example:
    Dim k As Variant
    For Each k In dict.Keys
        Debug.Print k & ": " & dict(k)
    Next k
  9. Remove items – Use .Remove for a single key, or .RemoveAll to clear everything:
    dict.Remove "Banana"   ' removes Banana
    dict.RemoveAll          ' empties the dictionary
  10. Get the count – Use the .Count property:
    MsgBox dict.Count
  11. 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.
  12. 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
  13. Clean up – When done, set the dictionary object to Nothing to free memory (especially in long-running macros):
    Set dict = Nothing

Common Mistakes

  • Adding a duplicate key – Causes runtime error 457. Always check Exists before adding.
  • Forgetting to set the reference – If you declare as Scripting.Dictionary without the reference, you’ll get a compile error. Use late binding or add the reference.
  • Using .Add on 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 = vbTextCompare before adding items.
  • Not clearing the dictionary between runs – If you reuse a dictionary variable, it retains old data. Use .RemoveAll or set to Nothing.
  • Using dict(key) when key doesn’t exist – This adds the key with an empty value (default behavior) and can cause subtle bugs. Always check Exists first for reading.

Tips

  • Use early binding when possible – It gives you IntelliSense and better performance. Late binding is fine for portability.
  • Set CompareMode early – 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 .Items to get all values at once – You can assign dict.Items to a variant array and write it directly to a range with Range.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.Dictionary without adding the reference. Either add the reference (Tools > References) or switch to late binding with CreateObject.
  • Runtime error 457: “This key is already associated with an element” – You tried to add a duplicate key. Check Exists before adding, or use dict(key) = value to 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 = vbTextCompare before adding items.
  • Macro works on Windows but fails on Mac – The Scripting.Dictionary is available on Mac in recent Excel versions, but if you use late binding, ensure the ProgID is correct. On Mac, you may need to use CreateObject("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 as Object. This is late binding and works without the reference.
  • How do I make dictionary keys case-insensitive? – Set the CompareMode property to vbTextCompare immediately 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.Match or Find? – For repeated lookups on a large dataset, a dictionary is usually faster because it uses hashing for O(1) average lookup, while Match and Find are O(n) or worse. For a one-off lookup, Match may be simpler.

Related

Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.

More in VBA & macros

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.