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,531
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

Is there a shortcut key for strikethrough?
Ctrl+S is used for Save. Ctrl+5 is used for Strikethrough. Why Ctrl+5? When you use hashmarks to count |||| is 4, strike through to mean 5.
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,214,805
Messages
6,121,665
Members
449,045
Latest member
Marcus05

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