Cat On A Spreadsheet
If you're writing Excel VBA code that deals with large datasets, comparisons, or de-duplication, chances are you’ve written your fair share of nested loops. But nested loops are slow, hard to debug, and make your code bloated.
In last week's post I touched upon something that can help with that, namely the Scripting.Dictionary — a powerful object that turns slow, nested logic into lightning-fast, readable code.
In this post, you'll learn:
What a Dictionary is and why it's better than collections or arrays in many cases.
How to use it for lookups, frequency counts, de-duplication, and more.
Real-world examples and performance tips.
A Dictionary is a data structure that stores key-value pairs. Think of it like a super-efficient table where you can instantly look up a value based on a unique key — just like using VLOOKUP, but in VBA and lightning fast.
Basic structure:
The Key-based lookup is much faster than looping through arrays;
Easy existence checking - use .Exists() instead of searching;
Their size is dynamic, there is no need to resize like arrays;
Flexible key types - you can use anything, not just numbers. Strings and even dates are fine.
Dictionary version (much faster):
This version will run much faster, especially when dealing with larger data sets.
Want to count how many times each item appears in a column? Easy:
Let’s say you want to extract only unique values from a list:
This is way faster than looping with If Not InStr(...) or comparing against a list.
Let’s say you have two columns, one with product IDs from sales, and one with the master product list. You want to flag missing IDs in the sales list.
Use Exists() before Add() to avoid errors.
Keys are case-sensitive by default. Use .CompareMode = vbTextCompare to make them case-insensitive.
Combine dictionaries with arrays for extremely fast in-memory processing.
Duplicate keys cause an error on .Add. To avoid that, use .Exists() checks before adding or use .Item() to overwrite existing data.
There is no native sorting in dictionaries, but you can use Collection or arrays to sort the keys.
Only keys can be unique, which means that if you need a multi-key structure you should consider using a concatenated key instead - think "Region-Agent-Date".
Dictionaries are one of the most underused and powerful tools in Excel VBA. By learning to use them, you can:
Write cleaner code
Eliminate slow loops
Build more intelligent macros
If you're working with large data sets or repeated lookups, this tool is a must.
Cat On A Spreadsheet