测试数据如下:
code number
A10101 1000
A10102 230
A10103 200
A10201 7500
A10202 2340
A10203 3710
这个函数可以将两列作为一个range,然后赋值给dictionary:
Function RangeToDict2(ByVal R As Range) As dictionary
Set RangeToDict2 = New dictionary
i = 1
Do Until i >= (R.Rows.Count * R.Columns.Count)
RangeToDict2.Add R(i), R(i + 1)
i = i + 2
Loop
End Function
读出这个字典
Sub test()
Dim rng As Range
Dim kc As dictionary
Set rng = ActiveWorkbook.Worksheets(1).Range("a2:b7")
Set kc = RangeToDict2(rng)
Dim key As Variant
For Each key In kc.Keys
Debug.Print key, kc(key)
Next key
Debug.Print "ok", kc("A10101")
End Sub
结果:
A10101 1000
A10102 230
A10103 200
A10201 7500
A10202 2340
A10203 3710
ok
为何这行的 Debug.Print "ok", kc("A10101")
,其中kc("A10101")
没有1000,作为结果输出呢?