Home » excel » excel – VBA: Get value from dictionary

excel – VBA: Get value from dictionary

Posted by: admin May 14, 2020 Leave a comment


I tried using dictionaries in VBA. Microsoft Scripting Runtime is activated and I managed to fill it with the data I want (the For Each loop shows me as much). But then I didn’t get any further

Sub Report2()

    Dim wbAggr As Workbook, wbMonat As Workbook
    Dim wsAggr As Worksheet
    Dim iRow As Long, lRowAggr As Long
    Dim dict As Scripting.Dictionary
    Dim key As Variant

    Set dict = New Scripting.Dictionary
    Set wbAggr = ThisWorkbook
    Set wsAggr = ThisWorkbook.Sheets(1)

    lRowAggr = wsAggr.Cells(Rows.Count, 1).End(xlUp).Row

    For iRow = 2 To lRowAggr
        dict.Add wsAggr.Cells(iRow, "K"), iRow
    Next iRow

    For Each key In dict.Keys  '-> returns 2500 key+item pairs
        Debug.Print key, dict(key)
    Next key

    Debug.Print "dict.Keys(20): " & dict.Keys(20)
    Debug.Print "dict.Items(20): " & dict.Items(20)
    Debug.Print "dict.Exists('101010074'): " & dict.Exists("101010074")
    Debug.Print "dict.Exists(101010074): " & dict.Exists(101010074)
    Debug.Print "dict('101010074'): " & dict("101010074")
    Debug.Print "dict(101010074): " & dict(101010074)
    Debug.Print "VarType(dict.Keys(20)): " & VarType(dict.Keys(20))
End Sub

Output for the Debug.Print statements:

  • dict.Keys(20): 101010074
  • dict.Items(20): 22
  • dict.Exists(‘101010074’): False
  • dict.Exists(101010074): False
  • dict(‘101010074’):
  • dict(101010074):
  • edit: VarType(dict.Keys(20)): 8 (= string)

So if I’m reading this right (probably not), there is a key “101010074”, but then why does dict.Exists("101010074") return False?

Output of For Each loop with Debug.Print key, dict(key):

Output of <code>Debug.Print key, dict(key)</code>

How to&Answers:

The way you’re adding your key the dictionary is setting the key to the Range object and not the Value. Use the following instead

For iRow = 2 To lRowAggr
    dict.Add wsAggr.Cells(iRow, "K").Value2, iRow
Next iRow