VB Clear Scripting.Dictionary对象

mae*_*sto 5 excel vba excel-vba

我正在编写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
Run Code Online (Sandbox Code Playgroud)

在我这样做之前,我将项目添加到字典中,然后我尝试清除它,但test1将等于测试并等于我添加的nr个对象.

我究竟做错了什么 ?谢谢!

T. *_*bre 9

如果我在我的工作站上运行以下宏,它可以工作:

        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
Run Code Online (Sandbox Code Playgroud)

运行后,test1等于0,测试等于1.

确保已启用Option Explicit,并且您的变量名称中没有任何拼写错误.

此外,请确保您没有"On Error Resume Next"语句,因为它会隐藏代码中的错误.尝试在代码段之前放置"On Error Goto 0",以便Excel显示任何错误消息.

由于您将变量值设置为Nothing,并为其分配新的字典对象,因此它不可能保留预先存储的值.

我也尝试运行以下代码,它也给出了相同的结果:

        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
Run Code Online (Sandbox Code Playgroud)

希望有帮助......


ass*_*ias 5

您的代码看起来不错,尽管您将dict设置为空的2行并不需要重新创建它.

不确定它是否相关但是在某些版本的VBA IDE中存在错误:如果您在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
Run Code Online (Sandbox Code Playgroud)

以分步模式运行它,当在注释行上时,在d和上添加一个手表d("b").第二个Debug.Print将打印2.到目前为止,您可能会认为手表创建了一个条目,这很奇怪,因为您不希望手表有副作用.

再次运行宏:第一个 Debug.Print将打印2,你会发现字典已经有一个"b"键.

实际上,与我上面所说的相反,删除手表d("b")并重新运行宏将正确地重置字典.