【发布时间】: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