【问题标题】:VBA: Get value from dictionaryVBA:从字典中获取值
【发布时间】:2019-05-23 08:21:10
【问题描述】:

我尝试在 VBA 中使用字典。 Microsoft Scripting Runtime 被激活,我设法用我想要的数据填充它(For Each 循环向我展示了很多)。但后来我没有进一步了解

Sub Report2()

    Dim wbAggr As Workbook, wbMonat As Workbook
    Dim wsAggr As Worksheet
    Dim iRow As Long, lRowAggr As Long
    Dim dict As Scripting.Dictionary
    Dim key As Variant


    Set dict = New Scripting.Dictionary
    Set wbAggr = ThisWorkbook
    Set wsAggr = ThisWorkbook.Sheets(1)

    lRowAggr = wsAggr.Cells(Rows.Count, 1).End(xlUp).Row

    For iRow = 2 To lRowAggr
        dict.Add wsAggr.Cells(iRow, "K"), iRow
    Next iRow


    For Each key In dict.Keys  '-> returns 2500 key+item pairs
        Debug.Print key, dict(key)
    Next key

    Debug.Print "dict.Keys(20): " & dict.Keys(20)
    Debug.Print "dict.Items(20): " & dict.Items(20)
    Debug.Print "dict.Exists('101010074'): " & dict.Exists("101010074")
    Debug.Print "dict.Exists(101010074): " & dict.Exists(101010074)
    Debug.Print "dict('101010074'): " & dict("101010074")
    Debug.Print "dict(101010074): " & dict(101010074)
    Debug.Print "VarType(dict.Keys(20)): " & VarType(dict.Keys(20))
End Sub

Debug.Print 语句的输出:

  • dict.Keys(20): 101010074
  • dict.Items(20): 22
  • dict.Exists('101010074'): 假
  • dict.Exists(101010074): 错误
  • dict('101010074'):
  • dict(101010074):
  • 编辑:VarType(dict.Keys(20)): 8 (= string)

所以如果我没看错(可能不是),有一个键“101010074”,但是为什么dict.Exists("101010074") 会返回False

For Each 循环与Debug.Print key, dict(key) 的输出:

【问题讨论】:

  • 可能是因为您添加了一个值并且您要求的是一个字符串。字典对于格式、LCase 和 UCase 来说非常烦人...要检查键的值,正确的 sintax 是:Debug.Print dict(Key)
  • @Damin 你可以使用dict.CompareMode = TextCompare使字典不区分大小写
  • 在 Excel 文件中,该列被格式化为文本。即使键不是字符串,在这种情况下dict.Exists(101010074) 不应该返回True 吗?反正Debug.Print VarType(dict.Keys(20))返回8,这是一个字符串

标签: excel vba dictionary


【解决方案1】:

您在字典中添加键的方式是将键设置为Range 对象,而不是Value。请改用以下内容

For iRow = 2 To lRowAggr
    dict.Add wsAggr.Cells(iRow, "K").Value2, iRow
Next iRow

【讨论】:

  • 感谢您的回答。但是,它仍然会通过并显示所有条目。此外,如果dict.Add 先添加键然后添加项目,那么dict.Add wsAggr.Cells(iRow, "K"), iRow 应该导致101010074 成为键,因为这是存储在K 列中的内容
  • @NoNameNo123 看着它进一步意识到了这个问题 - 编辑了我的答案
  • 我知道它必须是一些简单的东西(要么就是这样,要么我正在失去理智)。谢谢你拯救我的理智!
  • @NoNameNo123 只是一个额外的观察。如果K 列中有重复值,您将遇到问题。使用行号作为键可能是值得的,因为这将是唯一的。
  • 很好的电话,感谢您的提示,但重点是 K 列充满了唯一值(对此我将比较另一列充满值)。祝你有美好的一天!
猜你喜欢
  • 2016-05-09
  • 2022-12-17
  • 1970-01-01
  • 1970-01-01
  • 2021-09-16
  • 2016-08-31
  • 2018-07-08
  • 2019-07-29
  • 1970-01-01
相关资源
最近更新 更多