October 21, 2019

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)

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

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

One thought on “What is Dictionary in Excel VBA

  1. Dear sir!

    I’m your follower and have been using your Excel VBA vidual tutorials most. I would like to create such bullet numbers using excel vba code so that if any data record with specific bullet number in serial is deleted among the various data, the related serial numbers of the given data auto-adjust in order after deletion. So, would you plz. solve my problem with a kind response?

    With best regards,
    NP Wonem

Comments are closed.