-1
我写了一个函数,它可以从Excel工作表中建立一个包含Key => Value对的词典。到目前为止,这工作得很好,但我发现当单元格具有相同的值时,我的指令可以有重复的键。VBA单元作为词典中的键
任何人都可以解释我这种行为吗?
Function CreateDictionaryBySheet(_
SheetName As String, _
Optional KeyColumn As Long = 1, _
Optional ValueColumn As Long = 2, _
Optional StartRow As Long = 2 _
) As Object
Dim MyDictionary As Object
Set MyDictionary = CreateObject("Scripting.Dictionary")
Worksheets(SheetName).Activate
Dim MaxRows As Long
MaxRows = GetNumberOfRows(SheetName, KeyColumn)
Dim Row As Long
For Row = StartRow To MaxRows
MyDictionary.Item(Cells(Row, KeyColumn)) = Cells(Row, ValueColumn)
Next Row
Set CreateDictionaryBySheet = MyDictionary
End Function
我写了这个循环来检查我的代码:
Sub Test()
Dim Key As Variant
Dim MyDictionary As Object
Set MyDictionary = CreateDictionaryBySheet("Config")
For Each Key In MyDictionary
MsgBox (Key & " => " & MyDictionary(Key))
Next Key
End Sub
假设细胞(2,1)和细胞(3,1)均为 “A” 和细胞(2,2) = 1和单元格(3,2)= 2我会看到两个msgboxes:一个具有“a => 1”和一个具有“a => 2”
这对我来说似乎很奇怪,因为我确实假设只看到一个msgbox即“a => 2”
感谢您的帮助! 彼得