Can I load a 2-column table into a VBA Dictionary with a single instruction?

JenniferMurphy

Well-known Member
Joined
Jul 23, 2011
Messages
2,535
Office Version
  1. 365
Platform
  1. Windows
Suppose I have a table like this one in a sheet.
Weighted Ratings.xlsm
CD
7ProductPart#
8AK42-X3
9BM21-44
10CDL402
11DMD3-902
12EGT35
MrExcel


Can I load it into a VBA Dictionary or Collection object so that I can search on the key (Product) and get back the value (Part#)?

Or do I need to do it in a loop one row at a time?
VBA Code:
Sub DictTest()

Const rnTable As String = "Table16"
Dim NumRows As Long
NumRows = Range(rnTable).Rows.Count
Debug.Print NumRows & " rows"

Dim DictTest As New Dictionary
Dim i As Long
For i = 1 To NumRows
  DictTest.Add Range(rnTable).Cells(i, 1).Value, Range(rnTable).Cells(i, 2).Value
Next i

For i = 1 To NumRows
  Debug.Print "Part# for product " & Range(rnTable).Cells(i, 1).Value _
        & " is " & Range(rnTable).Cells(i, 2).Value
Next i

End Sub

Thanks
 

Excel Facts

Highlight Duplicates
Home, Conditional Formatting, Highlight Cells, Duplicate records, OK to add pink formatting to any duplicates in selected range.
Once again, those are the values of the keys, which are the range objects themselves. Hence:

VBA Code:
    Dim dic As New Dictionary
    Dim K As Integer
    
    For K = 1 To 3
        dic(Range("A" & K)) = 1
    Next K
    With dic.Keys()(0)
        MsgBox "Keys are ranges:" & vbLf & _
        "Value: " & .Value & vbLf & _
        "Address: " & .Address & vbLf & _
        "Font name: " & .Font.Name
    End With
 
Upvote 0

Forum statistics

Threads
1,215,237
Messages
6,123,805
Members
449,127
Latest member
Cyko

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top