You're taking a shortcut that's not allowed; Dictionary.Add
is implemented such that it expects one key/value pair, and adds one item to the dictionary. If you need to add multiple items, you need multiple calls to Dictionary.Add
- there's no way around it.
A shortcut that would be allowed though, would be to just grab the values in any 2-column Range
and turn that into a dictionary, rather than taking any random two arrays that may or may not be the same size.
Make a function that takes a 2D array and turns it into a dictionary by treating the first column as unique keys, and the second column as values.
Public Function ToDictionary(ByVal keyValuePairs As Variant) As Scripting.Dictionary
If Not IsArray(keyValuePairs) Then Err.Raise 5
If GetDimensions(keyValuePairs) <> 2 Then Err.Raise 5 'see https://stackoverflow.com/q/6901991/1188513
Dim result As Scripting.Dictionary
Set result = New Scripting.Dictionary
Const KEYCOL = 1, VALUECOL = 2
Dim i As Long
For i = LBound(keyValuePairs, KEYCOL) To UBound(keyValuePairs, KEYCOL)
If result.Exists(keyValuePairs(i, KEYCOL)) Then Err.Raise 457
result.Add Key:=keyValuePairs(i, KEYCOL), Item:=keyValuePairs(i, VALUECOL)
Next
Set ToDictionary = result
End Function
Now you can turn any 2-column Range
into a Dictionary
like this:
Dim things As Scripting.Dictionary
Set things = ToDictionary(Sheet1.Range("A2:B21").Value)
Note that Range.Value
yields a 1-based, 2D Variant
array whenever it refers to multiple cells.