我正在编写一个Excel宏,并且在清除Scripting.Dictionary对象时遇到了困难
Dim test As Integer
test = CompListDict.Count
CompListDict.RemoveAll
Set CompListDict = Nothing
Set CompListDict = CreateObject("Scripting.Dictionary")
Dim test1 As Integer
test1 = CompListDict.Count在这样做之前,我将项添加到字典中,然后尝试清除它,但是test1将等于测试,等于我添加的对象的nr。
我做错什么了?谢谢!
发布于 2012-03-23 09:34:13
如果我在工作站上运行以下宏,它就能工作:
Set compListDict = CreateObject("Scripting.Dictionary")
compListDict.Add 1, "Test"
Dim test As Integer
test = compListDict.Count
compListDict.RemoveAll
Set compListDict = Nothing
Set compListDict = CreateObject("Scripting.Dictionary")
Dim test1 As Integer
test1 = compListDict.Count运行它之后,test1 = 0,测试等于1。
请确保选项显式启用,并且您的变量名没有任何键入。
另外,确保您没有一个“”语句,因为它将隐藏代码中的错误。尝试将"On Error Goto 0“放在代码段之前,以便Excel将显示任何错误消息。
由于要将变量值设置为空值,并为其分配一个新的字典对象,因此不可能保留预先存储的值。
我还尝试运行以下代码,它也提供了相同的结果:
Set compListDict = CreateObject("Scripting.Dictionary")
compListDict.Add 1, "Test"
Dim test As Integer
test = compListDict.Count
compListDict.RemoveAll
Dim test1 As Integer
test1 = compListDict.Count希望能帮上忙..。
发布于 2012-03-23 09:42:23
您的代码看起来不错,尽管您将dict设置为nothing并重新创建它的2行代码是不必要的。
不确定它是否相关,但是在某些版本的VBA中存在一个bug :如果您在dict(aKeyThatDoesNotExist)上添加了一个手表,它可能导致tgat键被添加到dict中,并且不可移动。我所知道的唯一解决方案是:重新启动Excel以清除内存。
编辑
用于Siddharth:用Excel 2003和2010进行测试。
写一本新书。
打开VBA IDE。
在Sheet1模块中键入以下内容:
Option Explicit
Sub test()
Dim d As Variant
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "a"
Debug.Print d.Count
'Add watch here on d and d("b")
Debug.Print d.Count
End Sub一步一步地运行它,在注释行上,在d和d("b")上添加一个手表。第二个Debug.Print将打印2。到目前为止,您可能会认为手表创建了一个条目,这是很奇怪的,因为您不会期望手表有副作用。
再次运行宏:first Debug.Print将打印2,您会注意到字典中已经有一个"b“键。
实际上,与我前面所说的相反,删除d("b")上的手表并重新运行宏将正确地重置字典。
https://stackoverflow.com/questions/9836660
复制相似问题