The short answer: in VBA, Dictionary.Add does not take a True argument, and there is no built-in Add method that accepts a boolean. The True you may have seen relates to the CompareMode property (TextCompare) or a common workaround where people check Exists before adding to avoid a runtime error. This article explains exactly how Dictionary.Add works, why you might think True is involved, and how to add items safely.
What the Dictionary Object Actually Is
The Dictionary object in VBA comes from the Microsoft Scripting Runtime library (scrrun.dll). It is not part of the core VBA language but is available after you go to Tools > References in the VBA editor and check Microsoft Scripting Runtime. A dictionary stores key-value pairs, where each key must be unique. Unlike a Collection, a Dictionary lets you check for a key’s existence quickly with the Exists method, and it exposes a CompareMode that controls how keys are compared.
The Add Method Signature
The Add method has exactly two parameters: Key and Item. The syntax is:
DictionaryObject.Add Key, Item
Both parameters are required. Key is the unique identifier (often a string or a number), and Item is the value you store. There is no third parameter, and no boolean flag. If you write dict.Add True, "value", you are actually using True as the key, not as an option. That is valid VBA because True is a boolean literal, and a boolean can be a key. But if you write dict.Add "key", "value", True, you will get a compile error because Add only accepts two arguments.
Where the “True” Misconception Comes From
Two common sources lead people to search for “VBA dictionary add true”. First, the CompareMode property accepts vbTextCompare (which equals 1) or vbBinaryCompare (which equals 0). Some code examples set dict.CompareMode = vbTextCompare right before adding items, and a reader might conflate that with the Add method. Second, many programmers write a helper pattern like:
If Not dict.Exists(key) Then
dict.Add key, item
End If
That If Not condition evaluates to True when the key does not exist, so the word “True” appears in the same line as the Add call. Neither of these means Add accepts a boolean parameter.
How to Add Items Without Errors
The most common error when using Add is trying to add a duplicate key. The Add method throws a runtime error 457 (“This key is already associated with an element of this collection”) if the key already exists. To avoid that, always check Exists first, or use the assignment syntax instead. The assignment syntax is:
dict(key) = item
This does not throw an error if the key exists; it updates the existing value. If the key does not exist, it creates a new entry. So if you want to add or update without worrying about duplicates, use the assignment syntax. If you want to strictly add only new keys and ignore duplicates, use the Exists check.
Choosing Between Add and Assignment
Here is a practical decision guide:
- Use
Addwhen you want to enforce that a key is new and you want an error if it already exists. This is useful for catching data problems. - Use
dict(key) = itemwhen you want to insert or update without error handling. This is faster to write and handles both cases. - Use
ExistsbeforeAddwhen you want to add only new keys but silently skip existing ones.
For example, to count word frequencies:
Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")
Dim word As Variant
For Each word In Array("apple", "banana", "apple")
If dict.Exists(word) Then
dict(word) = dict(word) + 1
Else
dict.Add word, 1
End If
Next
This adds the first occurrence and increments subsequent ones.
CompareMode and Case Sensitivity
The CompareMode property determines whether keys are case-sensitive. By default, a dictionary is binary compare, meaning “Apple” and “apple” are different keys. If you set dict.CompareMode = vbTextCompare (which equals 1), then keys are treated as case-insensitive. You must set CompareMode before adding any items; setting it after items exist will cause a runtime error. So if you see code like:
Set dict = CreateObject("Scripting.Dictionary")
dict.CompareMode = vbTextCompare
dict.Add "A", 1
That is correct. The vbTextCompare constant is actually 1, and True is also -1 in VBA, so they are not the same. Do not confuse them.
Common Problems and Solutions
Beyond the duplicate key error, two other issues come up. First, forgetting to set a reference: if you declare Dim dict As Dictionary without the reference, you get a compile error. Either add the reference or use CreateObject("Scripting.Dictionary") with As Object. Second, the dictionary is not persisted: it exists only in memory and disappears when the procedure ends. To save data, you must write it to a worksheet, a text file, or a database. Also, keys can be any data type, but using large strings as keys can slow down lookups; use numeric IDs when possible.
Frequently Asked Questions
Can I pass True to the Add method to make it case-insensitive?
No. Case-insensitivity is set via the CompareMode property, not the Add method. Set dict.CompareMode = vbTextCompare before adding keys.
What does the error “This key is already associated” mean?
It means you called Add with a key that already exists in the dictionary. Use Exists to check first, or use the assignment syntax dict(key) = value to update instead.
Is there a way to add multiple items at once?
No built-in method exists. You loop through an array or collection and call Add or assignment for each element. You can also use a For Each loop over a range of cells.
Why does my dictionary treat “A” and “a” as different?
Because the default CompareMode is binary, which is case-sensitive. Set CompareMode = vbTextCompare to treat them as equal.
Can I use a boolean as a key?
Yes, you can use True or False as keys, but it is rarely useful. The dictionary will treat True and False as distinct keys, so you can store two items.
Does the dictionary work in Excel for Mac?
Yes, the Scripting Runtime is available on Mac versions of Office, but you must still enable the reference. The behavior is identical to Windows.
Practical Example: Counting with a Dictionary
Here is a complete, working example that counts how many times each word appears in a range of cells. Save a copy of your workbook before running any macro, as macros cannot be undone with Ctrl+Z.
Sub CountWords()
Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")
dict.CompareMode = vbTextCompare ' case-insensitive
Dim cell As Range
Dim word As Variant
Dim words() As String
For Each cell In Selection
words = Split(cell.Value, " ")
For Each word In words
If Len(word) > 0 Then
If dict.Exists(word) Then
dict(word) = dict(word) + 1
Else
dict.Add word, 1
End If
End If
Next word
Next cell
' Output to a new sheet
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets.Add
ws.Range("A1").Value = "Word"
ws.Range("B1").Value = "Count"
Dim i As Long
i = 2
Dim key As Variant
For Each key In dict.Keys
ws.Cells(i, 1).Value = key
ws.Cells(i, 2).Value = dict(key)
i = i + 1
Next key
End Sub
This macro uses Split to break text into words, then adds or increments each word. The output is written to a new worksheet. Note that vbTextCompare makes the count case-insensitive, so “Apple” and “apple” count as the same word.
Related
- How to Do Data Entry in a Laptop: Step-by-Step
- Filtering for Duplicates in Excel: 4 Fast Ways
- JavaScript Random Number in Range: Simple Guide
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- VBA Find After: How Excel Chooses the Search Start CellIn Excel VBA, the After argument in Range.Find tells Excel which single cell to search after when beginning…
- How to Make a Logitech Macro (G Hub & Gaming Software)This guide shows you how to create a macro on a Logitech mouse or keyboard using Logitech G…
- Excel VBA Range Hyperlinks: Insert, Edit, and RemoveTo insert a hyperlink into an Excel range with VBA, use the worksheet’s Hyperlinks.Add method and set its…
- Excel VBA: Hide a Column RangeTo hide a range of columns with Excel VBA, set its Hidden property to True: use Columns("B:D").Hidden =…
- Excel Analysis ToolPak vs ToolPak VBA: Key DifferencesExcel’s Analysis ToolPak is the add-in for running built-in statistical and engineering analyses from the Data tab; Analysis…
- VBA Dictionary Functions and How to Use ThemIn VBA, a Dictionary is an object for storing unique keys alongside values, and its main functions are…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.