vba VBA中的字典是用空的键值对创建的

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18733780/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 23:16:24  来源:igfitidea点击:

Dictionary in VBA is created with empty key value pair

excelvbadictionary

提问by Cameel

After creating a new dictionary:

创建新字典后:

Dim teams as Dictionary
Set teams = New Dictionary

I noticed that it already contains empty key - value pair (teams.Count returns value of 1). How can I prevent this from happening or delete this pair? Is this normal behaviour?

我注意到它已经包含空的键值对(teams.Count 返回值为 1)。我怎样才能防止这种情况发生或删除这对?这是正常行为吗?

采纳答案by Cameel

If you are referencing the same Microsoft Scripting Runtimedictionary scrrun.dllas me - Excel 2010.

如果您引用的Microsoft Scripting Runtime字典scrrun.dll与我相同- Excel 2010。

enter image description here

在此处输入图片说明

Then the below code returns 0as the .Countof items after creation with no manipulation.

然后下面的代码在创建后0作为.Count项目返回,无需操作。

Sub SD()
    Dim teams As Dictionary
    Set teams = New Dictionary
    Debug.Print teams.Count
End Sub

I wouldn't know the reason why your dictionary returns 1, however I think a workaround it would be to simply use the .RemoveAllmethod of the Dictionaryobject

我不知道你的字典返回的原因1,但是我认为一种解决方法是简单地使用对象的.RemoveAll方法Dictionary

Sub SD()
    Dim teams As Dictionary
    Set teams = New Dictionary
    teams.RemoveAll
    Debug.Print teams.Count
End Sub

回答by Keith Twombley

I had the same experience and solved it.

我有同样的经历并解决了它。

I had a Watch expression set for a value in the dictionary. Somehow this kept the empty key/value pair in the dictionary (or kept readding it).

我为字典中的一个值设置了一个 Watch 表达式。不知何故,这在字典中保留了空的键/值对(或继续阅读)。

Removing the watch(es) and stepping through the code I now see the dictionary does not have the Empty/Empty item any longer.

取下手表并逐步执行代码,我现在看到字典不再有空/空项目。