-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」
感謝您的幫助! 彼得