VB清除Scripting.Dictionary对象
我正在写一个Excelmacros ,并且在清除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将等于testing,并等于我添加的对象的nr。
我究竟做错了什么 ? 谢谢!
如果我在我的工作站上运行下面的macros,它可以工作:
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,testing等于1。
确保启用了Option Explicit,并且在variables名中没有任何拼写错误。
此外,请确保您没有“On Error Resume Next”语句,因为它会隐藏代码中的错误。 尝试在代码片段之前放置“On Error Goto 0”,以便Excel将显示任何错误消息。
由于您将variables值设置为Nothing,并为其指定一个新的dictionnary对象,因此它应该不可能保留预先存储的值。
我也尝试运行下面的代码,它也给出了相同的结果:
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
希望有帮助…
你的代码看起来不错,虽然你把你的代码设置为空白并重新创build它的2行是没有必要的。
不知道是否有关系,但在某些版本的VBA IDE中有一个错误:如果你已经在dict(aKeyThatDoesNotExist)
上添加了一个监视器,它可能会导致tgat关键字被添加到字典中,而不是可移动的。 我知道的唯一解决scheme:重新启动Excel以清除内存。
编辑
Siddharth:使用Excel 2003&2010进行testing。
创build一本新书。
打开VBA IDE。
在Sheet1模块中input:
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.到目前为止,您可以认为手表创build了一个条目,这很奇怪,因为您不希望手表有副作用。
再次运行macros:第一个 Debug.Print
将打印2,您会注意到该字典已经有一个“b”键。
实际上,与上面所说的相反,删除d("b")
并重新运行macros将正确地重置字典。
- 如何使用c#轻松编辑excel文件中的单元格值
- VBA Excel:运行时错误'1004'object'_Worksheet'faile的方法'范围'
- eclipse插件抛出org.eclipse.e4.core.di.InjectionException:java.lang.NoClassDefFoundError:org / apache / poi / ss / usermodel / Row
- Postgres小数精度VS Excel
- macros插入
- 在Excel范围中使用variables
- 通过一个Excel筛选多列的单元格
- vba:variables未在activeCell中定义
- 从Excel 2007中打开一个Oracle .dmp文件