【发布时间】:2016-10-22 09:02:44
【问题描述】:
我编写了一个函数,该函数将使用 Excel 工作表中的 Key => Value 对构建字典。到目前为止这工作正常,但我发现我的字典可以有重复的键,当单元格具有相同的值时。
谁能解释一下这种行为?
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我将看到两个msgbox:一个带有“ a => 1" 和一个 "a => 2"
这对我来说似乎很奇怪,因为我确实假设只看到一个 msgbox,即“a => 2”
感谢您的帮助! 彼得
【问题讨论】:
标签: excel dictionary key vba