【问题标题】:VBA Cells as Keys in DictionaryVBA 单元格作为字典中的键
【发布时间】: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


    【解决方案1】:

    哦,我刚刚发现我在引用单元格值时得到了假定的行为:

    这将允许重复值:

        MyDictionary.Item(Cells(Row, KeyColumn)) = Cells(Row, ValueColumn)
    

    这不是:

        MyDictionary.Item(Cells(Row, KeyColumn).Value) = Cells(Row, ValueColumn).Value
    

    我猜这是因为 dictinary 在第一种情况下确实将 Cells-Object 作为键,这不是本意的。

    【讨论】:

      猜你喜欢
      • 2020-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-10
      • 1970-01-01
      • 2020-09-25
      • 1970-01-01
      相关资源
      最近更新 更多