Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
Webinars About
Contents [hide]
https://excelmacromastery.com/vba-dictionary/ 1/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
https://excelmacromastery.com/vba-dictionary/ 2/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
Function Example
https://excelmacromastery.com/vba-dictionary/ 3/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
add it. Imagine we are storing the count of different fruit types.
In both cases, we are storing the value 5 and giving it the name “Apple”. We can now get
the value of Apple from both types like this
https://excelmacromastery.com/vba-dictionary/ 4/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
The VBA Dictionary does not have these issues. You can check if a Key exists and you can
change the Item and the Key.
For example, we can use the following code to check if we have an item called Apple.
If dict.Exists("Apple") Then
dict("Apple") = 78
These may seem very simple differences. However, it means that the Dictionary is very
useful for certain tasks. Particularly when we need to retrieve the value of an item.
Dictionary Webinar
We useIfcookies
you aretoaensure
memberthat of
wethe
giveVBA Vault,
you the bestthen click on
experience onthe
our image
website.below
If you to accesstothe
continue use this site we will
webinar and the associated source code.
assume that you are happy with it.
Ok
https://excelmacromastery.com/vba-dictionary/ 5/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
When you want to find the definition of a word you go straight to that word. You don’t
read through every item in the Dictionary.
A second real world example is a phone book(remember those?). The Key in a phone
book is the name\address and the Item is the phone number. Again you use the
name\address combination to quickly find a phone number.
In Excel the VLookup function works in a similar way to a Dictionary. You look up an
item based on a unique value.
We use1.cookies
Adds three fruitthat
to ensure types andyou
we give a value forexperience
the best each to a on
Dictionary.
our website. If you continue to use this site we will
assume that you are happy with it.
2. The user is asked to enter the name of a fruit.
Ok
3. The code checks if this fruit is in the Dictionary.
https://excelmacromastery.com/vba-dictionary/ 6/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
' https://excelmacromastery.com/
Sub CheckFruit()
If dict.Exists(sFruit) Then
MsgBox sFruit & " exists and has value " & dict(sFruit)
Else
MsgBox sFruit & " does not exist."
End If
End Sub
This is a simple example but it shows how useful a Dictionary is. We will see a real world
example later in the post. Let’s look at the basics of using a Dictionary.
Creating a Dictionary
To use the Dictionary you need to first add the reference.
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will
1. Select Tools->References from thethat
assume Visual
youBasic menu.
are happy with it.
Ok
https://excelmacromastery.com/vba-dictionary/ 7/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
2. Find Microsoft Scripting Runtime in the list and place a check in the box beside it.
or
Creating a Dictionary in this way is called “Early Binding”. There is also “Late Binding”.
Let’s have a look at what this means.
In technical terms Early binding means we decide exactly what we are using up front.
With Late binding this decision is made when the application is running. In simple terms
the difference is
(*Intellisense is the feature that shows you the available procedures and properties of
an item as you are typing.)
While Microsoft recommends that you use early binding in almost all cases I would differ.
A good rule of thumb is to use early binding when developing the code so that you have
access to the Intellisense. Use late binding when distributing the code to other users to
prevent various library conflict errors occurring.
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will
assume that you are happy with it.
Ok
https://excelmacromastery.com/vba-dictionary/ 8/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
We can add items to the dictionary using the Add function. Items can also be added by
assigning a value which we will look at in the next section.
Let’s look at the Add function first. The Add function has two parameters: Key and Item.
Both must be supplied
In the first add example above we use the parameter names. You don’t have to do this
although it can be helpful when you are starting out.
The Key can be any data type. The Item can be any data type, an object, array, collection
or even a dictionary. So you could have a Dictionary of Dictionaries, Array and
Collections. But most of the time it will be a value(date, number or text).
If we add a Key that already exists in the Dictionary then we will get the error
https://excelmacromastery.com/vba-dictionary/ 9/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
Assigning a Value
Operation Format Example
dict("Orange") = 75
Assigning a value to Key this way has an extra feature. If the Key does not exist it
automatically adds the Key and Item to the dictionary. This would be useful where you
had a list of sorted items and only wanted the last entry for each one.
Don’t forget that you can download all the VBA code used in this post from the top or
bottom of the post.
We can use the Exists function to check if a key exists in the dictionary
https://excelmacromastery.com/vba-dictionary/ 10/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
We could use an array or collection as the value but this is unnecessary. The best way to
do it is to use a Class Module.
You can see that by using the Class Module we can store as many fields as we want.
Examples 2 and 3 at the bottom of the post show how to use a class module with a
Dictionary
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will
https://excelmacromastery.com/vba-dictionary/ 11/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
The following sub shows an example of how you would use these functions
' https://excelmacromastery.com/
Sub AddRemoveCount()
End Sub
Remember that you can download all the code examples from the post. Just go to the
download section at the top.
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will
assume that you are happy with it.
Ok
https://excelmacromastery.com/vba-dictionary/ 12/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
© BigStockPhoto.com
The Dictionary uses a similar method. The CompareMode property of the Dictionary is
used to determine if the case of the key matters. The settings are
vbBinaryCompare: Upper and lower case are considered different. This is the default.
With the Dictionary we can use these settings to determine if the case of the key matters.
' https://excelmacromastery.com/
Sub CaseMatters()
https://excelmacromastery.com/vba-dictionary/ 13/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
End Sub
This time we use vbTextCompare which means that the case does not matter
' https://excelmacromastery.com/
Sub CaseMattersNot()
' Prints true because it considers Orange and ORANGE the same
Debug.Print dict.Exists("ORANGE")
End Sub
Note: The Dictionary must be empty when you use the CompareMode property or you
will get the error: “Invalid procedure call or argument”.
Orange, 5
orange, 12
The following code will create two keys – on for “Orange” and one for “orange”. This is
subtle as the only difference is the case of the first letter.
' https://excelmacromastery.com/
Sub DiffCase()
dict.Add
We use cookies Key:=(Range("A1")),
to ensure that Item:=Range("B1")
we give you the best experience on our website. If you continue to use this site we will
assume that youItem:=Range("B2")
dict.Add Key:=(Range("A2")), are happy with it.
Ok
https://excelmacromastery.com/vba-dictionary/ 14/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
End Sub
If you do use vbTextCompare for the same data you will get an error when you try to
add the second key as it considers “Orange” and “orange” the same.
' https://excelmacromastery.com/
Sub UseTextcompare()
End Sub
If you use the assign method then it does not take the CompareMode into account. So
the following code will still add two keys even though the CompareMode is set to
vbTextCompare.
' https://excelmacromastery.com/
Sub Assign()
' Prints 2
Debug.Print dict.Count
End Sub
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will
assume that you are happy with it.
Reading through the Dictionary
Ok
https://excelmacromastery.com/vba-dictionary/ 15/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
We can read through all the items in the Dictionary. We can go through the keys using a
For Each loop. We then use the current key to access an item.
Dim k As Variant
For Each k In dict.Keys
' Print key and value
Debug.Print k, dict(k)
Next
We can also loop through the keys although this only works with Early Binding(Update
Feb 2020: In Office 365 this now works with both versions):
Dim i As Long
For i = 0 To dict.Count - 1
Debug.Print dict.Keys(i), dict.Items(i)
Next i
Dim i As Long
For i = 0 To dict.Count - 1
Debug.Print dict.Keys()(i), dict.Items()(i)
Next i
The Dictionary doesn’t have a sort function so you have to create your own. I have
written two sort functions – one for sorting by key and one for sorting by value.
Sorting by keys
To sort the dictionary by the key you can use the SortDictionaryByKey function below
' https://excelmacromastery.com/
Public Function SortDictionaryByKey(dict As Object _
We use cookies to ensure that we give you the bestsortorder
, Optional experience onAs
ourXlSortOrder
website. If you continue to use this siteAwe will
= xlAscending)
assume that you are happy with it.
https://excelmacromastery.com/vba-dictionary/ 16/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
' Read through the sorted keys and add to new dictionary
For Each key In arrList
dictNew.Add key, dict(key)
Next key
' Clean up
Set arrList = Nothing
Set dict = Nothing
End Function
' https://excelmacromastery.com/
Sub TestSortByKey()
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will
assume that you are happy with it.
Dim dict As Object
Ok
Set dict = CreateObject("Scripting.Dictionary")
https://excelmacromastery.com/vba-dictionary/ 17/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
dict.Add "Plum", 99
dict.Add "Apple", 987
dict.Add "Pear", 234
dict.Add "Banana", 560
dict.Add "Orange", 34
End Sub
Sorting by values
To sort the dictionary by the values you can use the SortDictionaryByValue function below.
' https://excelmacromastery.com/
Public Function SortDictionaryByValue(dict As Object _
, Optional sortorder As XlSortOrder = xlAscending)
We use cookies
Onto Error
ensure that
GoTowe give
eh you the best experience on our website. If you continue to use this site we will
assume that you are happy with it.
Ok
Dim arrayList As Object
https://excelmacromastery.com/vba-dictionary/ 18/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
value = dict(key)
End If
Next key
dict.RemoveAll
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will
assume that you are happy with it.
' Read through the ArrayList and add the values and corresponding
Ok
' keys from the dictTemp
https://excelmacromastery.com/vba-dictionary/ 19/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
Done:
Exit Function
eh:
If Err.Number = 450 Then
Err.Raise vbObjectError + 100, "SortDictionaryByValue" _
, "Cannot sort the dictionary if the value is an objec
End If
End Function
' https://excelmacromastery.com/
Sub TestSortByValue()
dict.Add "Plum", 99
dict.Add "Apple", 987
dict.Add "Pear", 234
dict.Add "Banana", 560
dict.Add "Orange", 34
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will
' Sort Ascending
assume that you are happy with it.
Set dict = SortDictionaryByValue(dict)
Ok
PrintDictionary "Value Ascending", dict
https://excelmacromastery.com/vba-dictionary/ 20/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
End Sub
End Sub
Missing Reference
Issue: You get the error message “User-defined type not defined”
This normally happens when you create the Dictionary but forget to add the reference.
Resolution: Select Tools->Reference from the Visual Basic menu. Place a check in the box
beside “Microsoft Scripting Runtime”.
https://excelmacromastery.com/vba-dictionary/ 21/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
The following code adds “Apple” as a key. When we check for “apple” it returns false. This
is because it takes the case of the letters into account:
dict.Add "Apple", 4
If dict.Exists("apple") Then
MsgBox "Exists"
Else
MsgBox "Does not Exist"
End If
You can set the CompareMode property to vbTextCompare and this will ignore the case:
Resolution: Set the CompareMode to vbTextCompare to ignore case or ensure your data
has the correct case.
The normally happens when you forget to use New before you use the Dictionary. For
example, the following code will cause this error
Or
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will
Dim dict As Scripting.Dictionary
assume that you are happy with it.
Set dict = New Scripting.Dictionary
Ok
https://excelmacromastery.com/vba-dictionary/ 22/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
Use the following sub to Print each Key and Item to the Immediate Window(Ctrl + G).
' https://excelmacromastery.com/
Sub PrintContents(dict As Scripting.Dictionary)
Dim k As Variant
For Each k In dict.Keys
' Print key and value
Debug.Print k, dict(k)
Next
End Sub
If you are stepping through the code you can also add dict.Count to the Watch Window
to see how many items are currently in the Dictionary. Right-click anywhere in the code
window and select Add Watch. Type dict.Count into the text box and click Ok.
You can also use the Dictionary itself as a Watch. Add Dict to the Watch window. If you
click on the plus sign you will see the contents of the Dictionary. This can be useful but it
only shows the key and not the item.
Note: You can only view Watches when the code is running.
https://excelmacromastery.com/vba-dictionary/ 23/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
As both of these properties are arrays, we can write them directly to a worksheet as we
will see in the next section.
If we want to copy either the Keys or Items array to a new array then we can do it very
easily like this:
The following example copies the Keys and Items arrays to new arrays. Then the contents
of the new arrays are printed to the Immediate Window:
Sub DictionaryToArray()
https://excelmacromastery.com/vba-dictionary/ 24/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
End Sub
End Sub
When you run the code you wil get the following output:
https://excelmacromastery.com/vba-dictionary/ 25/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
When you write out the keys or items they will be written to a row. If you want to write
them to a column you can use the WorksheetFunction.Transpose function.
The code below shows examples of how to write the Dictionary to a worksheet:
Sub DictionaryToWorksheet()
dict.Add "France", 56
dict.Add "USA", 23
dict.Add "Australia", 34
Dim sh As Worksheet
Set sh = ThisWorkbook.Worksheets("Sheet1")
End Sub
https://excelmacromastery.com/vba-dictionary/ 26/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
workbooks and code for these examples by entering your email below:
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will
Our task here is to get the number of goals scored by each team.
assume that you are happy with it.
Ok
https://excelmacromastery.com/vba-dictionary/ 27/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
The first thing we need to do is to read all the data. The following code reads through all
the matches and prints the names of the two teams involved.
' https://excelmacromastery.com/vba-dictionary
' Reads the World Cup data from the 2014 Worksheet
' View the results in the Immediate Window(Ctrl + G)
Sub GetTotals()
Dim i As Long
For i = 2 To rg.Rows.Count
' read the data from each match
Team1 = rg.Cells(i, 5).Value
Team2 = rg.Cells(i, 9).Value
Goals1 = rg.Cells(i, 6).Value
Goals2 = rg.Cells(i, 7).Value
' Print each teams/goals to Immediate Window(Ctrl + G)
Debug.Print Team1, Team2, Goals1, Goals2
Next i
End Sub
What we want to do now is to store each team and the goals they scored. When we meet
a team for the first time we add the name as a Key and the number of goals as the Item.
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will
assume that you are happy with it.
Ok
https://excelmacromastery.com/vba-dictionary/ 28/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
If the team has already been added then we add the goals they scored in the current
match to their total.
We can use the following line to add goals to the current team:
If the teams exists in the Dictionary, the current goals are added to the current total for
that team.
If the team does not exist in the Dictionary then it will automatically add the team to the
Dictionary and set the value to the goals.
Key, Value
Brazil, 5
Then
dict("Brazil") = dict("Brazil") + 3
We usewill update
cookies the dictionary
to ensure soyou
that we give it now looks
the best like this on our website. If you continue to use this site we will
experience
assume that you are happy with it.
Key, Value
Ok
https://excelmacromastery.com/vba-dictionary/ 29/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
Brazil, 8
The line
dict("France") = dict("France") + 3
Key, Value
Brazil, 8
France, 3
If dict.Exists(Team1) Then
' If exists add to total
dict(Team) = dict(Team) + Goals1
Else
' if doesn't exist then add
dict(Team) = Goals1
End If
We write out the values from the Dictionary to the worksheet as follows:
End Sub
We useWe obviously
cookies want
to ensure the
that wescores tothe
give you bebest
sorted. It is much
experience easier
on our to read
website. If youthis way.toThere
continue is no
use this site we will
https://excelmacromastery.com/vba-dictionary/ 30/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
What we can do is sort the data once it has been written to the worksheet. We can use
the following code to do this:
Dim rg As Range
Set rg = shReport.Range("A1").CurrentRegion
rg.Sort rg.Columns("B"), sortOrder
End Sub
' https://excelmacromastery.com/vba-dictionary
Sub GetTotalsFinal()
https://excelmacromastery.com/vba-dictionary/ 31/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
Next i
' Clean up
Set dict = Nothing
shReport.Activate
End Sub
When you run this code you will get the following results
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will
Teams ordered by number of goals scored
assume that you are happy with it.
Ok
https://excelmacromastery.com/vba-dictionary/ 32/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
Imagine this data starts at cell A1. Then we can use the code below to read to the
dictionary.
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will
' Standard module Code
assume that you are happy with it.
' https://excelmacromastery.com/
Ok
Sub Main()
https://excelmacromastery.com/vba-dictionary/ 33/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
End Sub
' Get the range of all the adjacent data using CurrentRegion
Dim rg As Range
Set rg = sh.Range("A1").CurrentRegion
https://excelmacromastery.com/vba-dictionary/ 34/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
Next i
End Function
Next key
End Sub
https://excelmacromastery.com/vba-dictionary/ 35/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
Next key
End Sub
This time there will be multiple entries for some customers and we want to sum the total
Amount and total Items for each customer.
Note: If you run the “Example 2” code on data with multiple copies of the CustomerID, it
will give the “Key already exists error”.
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will
' Read from worksheet: CustomerSum
assume that you are happy with it.
' Write to worksheet: CustomerRepSum
Ok
' https://excelmacromastery.com/vba-dictionary
https://excelmacromastery.com/vba-dictionary/ 36/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
Sub MainSum()
End Sub
' Read multiple items but this time sums the items
' https://excelmacromastery.com/
Private Function ReadMultiItemsSum() As Dictionary
' Get the range of all the adjacent data using CurrentRegion
Dim rg As Range
Set rg = sh.Range("A1").CurrentRegion
https://excelmacromastery.com/vba-dictionary/ 37/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
Next i
End Function
Next key
End Sub
https://excelmacromastery.com/vba-dictionary/ 38/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
Next key
End Sub
1. You have a list of unique items e.g. countries, invoice numbers, customer name and
addresses, project ids, product names etc.
2. You need to retrieve the value of a unique item.
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will
assume that you are happy with it.
Ok
2
https://excelmacromastery.com/vba-dictionary/ 39/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
2
Key/Values of Countries and Land area in Km
What’s Next?
Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills
then why not try out the The Ultimate VBA Tutorial.
Related Training: Get full access to the Excel VBA training webinars and all the tutorials.
(NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA
applications from scratch.)
228 Comments
← Older Comments
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will
V BALACHANDRAN on you
assume that Juneare
11,happy
2020with
at 4:17
it. am
Ok
https://excelmacromastery.com/vba-dictionary/ 40/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
Reply
David on June 19, 2020 at 3:11 pm
Hi,
I successfully managed to read data from a closed workbook & storing the
excel data sheet (it’s rows/columns values) into an array() variant. All
works smoothly with the exception that some rows contain more than
255 characters. I’m not getting any error message but the text is simply
cut up and until it reaches the 255 character. Is there a way I could
increase that maximum limit by using one of the above possibilities such
as Dictionaries, Arraylist or Collection? Thanks in advance for your prompt
response.
Reply
Reply
https://excelmacromastery.com/vba-dictionary/ 41/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
Reply
Reply
Sam on October 13, 2020 at 1:42 pm
Very nice reference. Is the only way to do a multidimensional dictionary
(i.e., a first and a second key) to store a collection or a dictionary inside
another dictionary? I’ve always found that method a bit clunky.
Reply
Reply
Reply
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will
Paul Kelly on November 11, 2020 at 10:12 am
assume that you are happy with it.
Ok
https://excelmacromastery.com/vba-dictionary/ 42/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
Reply
Philip Petev on February 13, 2021 at 6:07 pm
I thinks there’s an unused variable in the SortDictionaryByKey functions
It seems coll is declared, but never used, not in this function anyway…
Reply
Reply
mItems = dict.Items
mKeys = dict.Keys
For i = 0 To dict.Count – 1
If IsNumeric(mItems(i)) = True Then
isNumber = True
Else
isNumber = False
End If
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will
Next
assume that you are happy with it.
Ok
https://excelmacromastery.com/vba-dictionary/ 43/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
and convert the values if they are all numeric in the section where the
ArrayList is generated like this
This way the result of the function sorts the dictionary correctly if there
are only numeric values.
I think that this way the function works more like excel would sort in a
table.
You have a great blog that illustrates so much for everybody that gets into
VBA. Thank you for sharing
your knowledge.
Cheers, Oliver
Reply
Monica on May 5, 2021 at 5:25 pm
Thank you for a GREAT resource!
Could you help me understand if it’s possible to use multiple key fields as
a UID with the dictionary? I’m trying to compare two sheets; the same
data feed but at different points in time. Each row is unique base on the
combination of the PO document number, line item number and a
delivery date. I’d like to identify when all changes from between the two
points in time but not sure how to match the data. Any recommendations
on a technique that could work?
Reply
Reply
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will
assume that you are happy with it.
Ok
https://excelmacromastery.com/vba-dictionary/ 44/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
Reply
Reply
Thank you for creating and publishing your website & YouTube Channel,
they are a great help as I learn VBA! I am developing an Excel Application
and look forward to working through The Excel VBA Handbook in the very
near future!
Thanks again!
Reply
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will
assume that you are happy with it.
Ok
https://excelmacromastery.com/vba-dictionary/ 45/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
You can use a for loop with Debug.Print to the print the contents
to the Immediate Window.
-Paul
Reply
Steve Wombat on August 3, 2021 at 5:42 am
Comprehensive and extrememly helpful, thanks for this, amazing work.
Reply
Reply
When I click on the “Create Report” button to run the macro, I get a run-
time error at the codeline I just pasted above:
Run-time Error ‘438’:
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will
Object doesn’t assume
supportthat
thisyou
property or method
are happy with it.
Ok
https://excelmacromastery.com/vba-dictionary/ 46/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
So there is something wrong with the syntax for this line “For Each key In
Dict”
Do I need to use something other than a For Each loop or does the key
need any qualifiers added to it? I really don’t know this is the first time I
have ever worked with a Dictionary in Excel. Any and all help would be
most appreicated. I have went through a lot of your videos and they are
all awesome. I have learned a lot!!
Jason
Reply
Try this:
For Each Key in Dict.Keys
Paul
Reply
Reply
David on August 22, 2021 at 6:14 pm
Hello Paul,
First of all, thank you very much for all of your guides, they are extremely
clear and helpful.
Using your dictionary guide I have written a code to read through a
filtered column range.
As per your suggestion I wrote it first by using Early Binding, and it
worked.
Afterwards I wrote a new code, copying the one from before but changing
it to Late Binding.
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will
I can read the filtered
assume column andhappy
that you are i get with
a dictionary
it. where the keys are
the row number and the items Ok
are the value on each row.
But when I tried to debug print the keys and items I got the error:
https://excelmacromastery.com/vba-dictionary/ 47/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
Property let procedure not defined and property get procedure did not
return an object (Error 451)
Could you clarify to me why this error pops up?
Thank you very much in advance.
End Sub
NumberOfAreas = ColRng.Areas.count
ReDim RngAddressArray(0 To NumberOfAreas – 1)
RngAddressArray = Split(ColRng.Address, “,”)
End
We use cookies to ensure thatFunction
we give you the best experience on our website. If you continue to use this site we will
assume that you are happy with it.
Private Function ReadColRangeAddress(RColDict,
Ok
RngAddress As Variant)
https://excelmacromastery.com/vba-dictionary/ 48/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
As Object
End Function
Reply
Vic Asp on October 22, 2021 at 7:30 pm
Paul,
Thank you so much for the great VBA articles, I have learned so much. I
am having one problem though I can’t get passed.
sub Main()
Dim dict As New Dictionary
‘fill dictionary
Call Routine(dict)
end
We use cookies to ensure thatsub
we give you the best experience on our website. If you continue to use this site we will
assume that you are happy with it.
sub Routine(dict As Dictionary)
Ok
x = dict.count <—— Compile error: Constant expression required
https://excelmacromastery.com/vba-dictionary/ 49/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
end sub
If I code around this problem I can use dict.keys later with no problems.
Any help would be greatly appreciated.
Thanks,
Vic
Reply
-Paul
Reply
sandeep on November 4, 2021 at 3:29 am
Great article & great webinar.
Reply
Reply
this is my first online post regarding VBA. Your guide was superb and I
was able to improve a lot of my tools with dictionaries.
Value = MydictValues.Item(strTimestamp)
End Property
Whenever my code ran this line, it added the string as a new key to the
dictionary if it wasn’t already a key. This became a huge issue. I thought
this line just gets the value of the key and if the key does not exist it
returns null.
If MydictValues.Exists(strTimestamp) Then
Value = MydictValues.Item(strTimestamp)
Else
Err.Raise Number:=1, Description:=”Es wurde für Zeitstempel ein Wert
abgefragt, welcher nicht existiert.”
End If
End Property
Reply
https://excelmacromastery.com/vba-dictionary/ 51/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
investing time to check out that those clean-up sections are well
implemented everywhere in the code.
Reply
Joseph on March 28, 2022 at 2:20 pm
Paul – all of your stuff is so great. Thank you.
Reply
Reply
Reply
Would it be best to create 15 dictionaries one for each field and have the
key
We use cookies to ensure forweeach
that give dictionary
you the bestlinked to the
experience oncustomer IDIfor
our website. yourow number
continue from
to use this site we will
https://excelmacromastery.com/vba-dictionary/ 52/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
Reply
joe on October 31, 2022 at 4:19 pm
Hi Paul, This is my first time posting and I wanted to thank you for the
excellent articles. Can you help me understand what is ClearData function
that’s used in the below WriteDictionary Sub? I don’t see it defined
anywhere in this article. Thank you.
ClearData shReport
End Sub
Reply
Reply
but some of them don’t have a “tomlInfo” key, so it’s giving me a Type
Mismatch error when I try accessing Rec(“tomlInfo”)(“orgName”).
My VBA (snippet):
Dim Recs As Collection
Set Recs = AResp(“_embedded”)(“records”) ‘ Response parsed with
JSONconverter
Is there a good way to skip this part if that key doesn’t exist? I tried using
dict.exists, but I don’t know how to use that with nested dictionaries like
these…
Thanks
We use cookies to ensure that wefor your
give you time
the best experience on our website. If you continue to use this site we will
assume that you are happy with it.
Ok Reply
https://excelmacromastery.com/vba-dictionary/ 54/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
Reply
Reply
Reply
← Older Comments
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will
assume that you are happy with it.
Ok
https://excelmacromastery.com/vba-dictionary/ 55/56
2/29/24, 10:35 PM Excel VBA Dictionary - A Complete Guide - Excel Macro Mastery
Password:
Remember Me
Login
» Register
» Lost your Password?
Designed by Elegant Themes | Powered by WordPress
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will
assume that you are happy with it.
Ok
https://excelmacromastery.com/vba-dictionary/ 56/56