Excel VBA Dictionary and Collection: group values by key

A Dictionary stores pairs of key and value, such as region and sales, and every key appears only once. That lets you build a total per group in a single line, look up prices the way VLOOKUP does, or spot duplicates.

In short: Set d = CreateObject("Scripting.Dictionary") creates a Dictionary. d(region) = d(region) + amount adds up per region, even when the region is not there yet. d.Exists(x) asks whether a key exists, and d.Keys and d.Items return all keys and values as an array.

What you need to know: arrays and loops with For Each.

Try it right now

The sales rows are in no particular order and every region shows up several times. You want a small summary instead: each region once, with its total next to it. That is exactly the job a Dictionary does well.

Task The macro TotalByRegion should add up sales per region: each region once in column D (from D2, in the order it first appears), with its total next to it in E. Use a Dictionary with the region as key. Check tests with more rows and an extra region.

ABCDE
1RegionSalesRegionTotal
2North1,200.00
3South850.00
4North430.00
5West990.00
6South1,510.00
7North275.00

How a Dictionary works

Dim d As Object, k As Variant
Set d = CreateObject("Scripting.Dictionary")
d("North") = d("North") + 1200    ' North is new: Empty + 1200 = 1200
d("South") = d("South") + 850
d("North") = d("North") + 430     ' North is now 1630
For Each k In d.Keys
    Debug.Print k, d(k)
Next k

The Immediate window then shows two lines, North with 1630 and South with 850. Keys stay in the order they were added.

CommandWhat it does
d(k) = valueSets the value for key k. If k does not exist, it is created.
d(k)Reads the value. Careful: if k does not exist, even reading creates the key with an empty value.
d.Add k, valueAdds a new entry. If k already exists, you get a run-time error.
d.Exists(k)True or False, without creating anything.
d.CountNumber of entries.
d.Keys, d.ItemsAll keys or all values as an array, starting at index 0.
d.Remove kRemoves one entry.

That reading a missing key creates it is documented by Microsoft for the Item property. It is what keeps the totals line so short: the first time, d(k) + amount is Empty plus the amount, which is the amount. When you are looking things up, the same behaviour is a trap, and that is what Exists is for.

Looking up with Exists

Load a price list into a Dictionary once and every price is found instantly, without searching the sheet. If an item is missing, you want to see that, not have it slip through as 0.

Task The price list is on the left, the orders on the right. The macro OrderAmounts should load the price list into a Dictionary (item as key, price as value) and then put quantity times price in column F for every order. If the item is not in the price list, F gets the text "unknown". Test for that with .Exists.

ABCDEF
1ItemPriceOrderedQtyAmount
2P-1004.85P-21525
3P-14064.90P-10010
4P-2152.40P-9993
5P-2300.65P-31012
6P-3101.95

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

Collection: the simple list

VBA also has the built-in Collection. It needs no CreateObject and keeps items in a row, optionally with a key:

Dim c As New Collection
c.Add "Carter Bakery"
c.Add "Peters Motors"
Debug.Print c.Count, c(1)       ' 2, Carter Bakery

For totals per group a Collection is clumsy: it has no Exists, and a stored value cannot be changed, only removed and added again. Asking for a key that is not there gives "Run-time error '5': Invalid procedure call or argument". It is fine for lists you only collect and loop through later. For anything with keys, use the Dictionary.

Find the bug

Add sounds like the obvious way to add something. For counting it is exactly wrong, as soon as a customer shows up a second time.

Task Find the bug: the macro CountOrders should count how many orders each customer has (customer in D, count in E, from row 2). Instead it stops with "Run-time error '457': This key is already associated with an element of this collection". Get it running without changing the output.

ABCDE
1CustomerOrderCustomerOrders
2Carter BakeryA-501
3Peters MotorsA-502
4Carter BakeryA-503
5Brandt ElectricalA-504
6Carter BakeryA-505
7Peters MotorsA-506

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

In real Excel

The Dictionary is not part of VBA itself but of the Microsoft Scripting Runtime. With CreateObject("Scripting.Dictionary") and Dim d As Object there is nothing to set up. If you would rather get the list of members while typing, tick "Microsoft Scripting Runtime" under Tools > References in the VBA editor and write Dim d As New Scripting.Dictionary. The exercises here understand both.

Text keys are case-sensitive: "North" and "north" are two entries. Clean the data first, or use UCase on the key.

Common mistakes

Duplicate key with Add

If the macro calls d.Add twice with the same key, it stops with "Run-time error '457': This key is already associated with an element of this collection". Use d(k) = ... instead, or check first with If Not d.Exists(k) Then.

Forgetting Set

A Dictionary is an object and is assigned with Set: Set d = CreateObject("Scripting.Dictionary"). If that line is missing, d is empty and the first access reports "Run-time error '91': Object variable or With block variable not set".

Numbers and text as keys

The number 100 and the text "100" are different keys to a Dictionary. If item codes come from the cells sometimes as numbers and sometimes as text, Exists will not find them. Convert them the same way when loading and when looking up, with CStr for example.

Looking up without Exists

prices("P-999") returns Empty for an unknown item, which calculates like 0. There is no message, just a wrong amount, and the item is now a key in the Dictionary.

FAQ

Dictionary or VLookup through WorksheetFunction?

For a single lookup, WorksheetFunction.VLookup is shorter. For many lookups inside a loop, the Dictionary is faster because the list is read only once. VLookup also raises a run-time error when the value is missing, which you have to catch. The next lesson shows how.

Why does d.Keys start at 0?

Keys and Items return an ordinary array, and VBA starts at 0 unless told otherwise. The first key is d.Keys()(0). With For Each you do not have to think about it.

Can a value in a Dictionary be an array itself?

Yes, a value can be anything: a number, text, an array or an object. For a count and a total per customer, two Dictionaries with the same keys are easier to read, though. That is how you do it in the project at the end of this level.

Learn this next: error handling

Macros run into missing sheets, empty cells and unknown items. With On Error you catch these errors and react on purpose instead of ending up in the Debug dialog.

Error handling

Write to us

Choose language

Select your preferred language