What is Dictionary in Excel VBA

What is a Dictionary in Excel VBA. An introduction to Dictionary object in VBA. A Dictionary object (ARRAY) that stores data key/item pairs.We need to activate the following library from Tools – References in the Visual Basic Editor: Scripting.Dictionary.
A Dictionary object is the equivalent of a PERL associative array. PERL is Practical Extraction and Report Language.
Associative arrays basically store tables of information.
When you declare an associative array the key and associated values are listed in consecutive pairs.

So if we had the following table:
name salary
Dave 25000
Aslam 30000
Krishna 32000

Watch the video below and then study the associate code on how to create a dictionary, proerties of Dictionary and methods used in Dictionary:

Here’s the complete VBA code used in this example:
Option Explicit

Sub WriteDictionary(mydictionary As Scripting.Dictionary, shtReport As Worksheet)

shtReport.Cells.Clear
Dim k As Variant, lRow As Long
lRow = 2
Range(“A1”) = “Customer ID”
Range(“B1”) = “Amount”
For Each k In mydictionary.Keys
shtReport.Cells(lRow, 1) = k
shtReport.Cells(lRow, 2) = mydictionary(k)
lRow = lRow + 1
Next

End Sub

Sub GetTotals()

‘ Create a dictionary
Dim mydictionary As New Scripting.Dictionary

‘ Get worksheet
Dim sht As Worksheet
Set sht = ThisWorkbook.Worksheets(“Sheet1”)

‘ Get range
Dim myRange As Range
Set myRange = sht.Range(“A1”).CurrentRegion

Dim customerID As String
Dim Amount As Long

Dim i As Long
For i = 2 To myRange.Rows.Count
customerID = myRange.Cells(i, 1)

Amount = myRange.Cells(i, 2)

mydictionary(customerID) = mydictionary(customerID) + Amount

Next i

‘ Get the report worksheet
Dim shtReport As Worksheet
Set shtReport = ThisWorkbook.Worksheets(“customerReport”)

‘ Write customer totals
WriteDictionary mydictionary, shtReport

‘ Clean memory
Set mydictionary = Nothing

End Sub

Further Reading:
Dictionary Object

Published by

Dinesh Kumar Takyar

Welcome to exceltrainingvideos.com! My aim is to help you learn MS Excel including VBA. I always felt that a good way to learn something was to find solutions to problems in that domain. That is why I share these Excel videos with you. Mostly these are questions asked during my corporate training sessions. I've been training individuals and companies in computers since 1991. I did my B. Sc. (Vordiplom), M. Sc. (Diplom) and Ph.D. (Dr. rer. nat.) from Hamburg, Germany. The best thing about solving some of my visitor's questions is that I also gain new insights. For more Excel VBA solutions you may like to visit my YouTube channel: http://youtube.com/familycomputerclub For a structured Excel VBA training course online you can visit: https://www.youtube.com/excelvbaonline

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.