【发布时间】:2022-11-03 19:29:45
【问题描述】:
我对 vba 字典很着迷,因为 Exists() 方法没有意义。
我虽然你可以使用 dict.Exists(key) 方法来检查一个键是否在字典中,而不需要进一步的操作。问题是在检查时,键会自动添加到字典中。真的没有意义!
这是我的代码。难道我做错了什么?
Function getContracts(wb As Workbook) As Dictionary
Dim cData As Variant, fromTo(1 To 2) As Variant
Dim contracts As New Dictionary, ctrDates As New Collection
Dim positions As New Dictionary, p As Long, r As Long
Dim dataSh As String, i As Long
dataSh = "Export"
cData = wb.Worksheets(dataSh).UsedRange
For i = LBound(cData) To UBound(cData)
fromTo(1) = cData(i, 1)
fromTo(2) = cData(i, 2)
Set ctrDates = Nothing
If IsDate(fromTo(1)) And IsDate(fromTo(2)) Then
If Not contracts.Exists(cData(i, 3)) Then ' Here it detects correctly that the key doesn't exist
ctrDates.Add fromTo
contracts.Add cData(i, 3), ctrDates ' And here it fails because the key just got added by .Exists()
Else
Set ctrDates = contracts(cData(i, 3))
ctrDates.Add fromTo
contracts(cData(i, 3)) = ctrDates
End If
Else
Debug.Print "Not a valid date in line " & i
End If
Next i
End Function
【问题讨论】:
-
它对
cData(i, 3)的所有值都失败还是仅对特定值失败? -
代码对我有用我的测试数据。确切的错误消息是什么?
cdata(i,3)的值是多少?顺便说一句,通常不需要检查是否存在,因为如果不存在,更改操作将添加密钥。 -
FunThomas:所有人都失败了。即使从中间窗口 Storax 输入它:它包含一个带有合同号的字符串(即:“054831”) VBasic2008:我会试试
-
你试过
Set contracts(cData(i, 3)) = ctrDates吗?在 Else 语句中contracts(cData(i,3)).Add FromTo? -
请在循环之前添加行
contracts.RemoveAll(不要问为什么......)并在Set contracts(cData(i, 3)) = ctrDates中转换contracts(cData(i, 3)) = ctrDates,正如已经建议的......
标签: vba dictionary