通过使用索引/项目编号的Scripting.Dictionary循环 [英] Looping through a Scripting.Dictionary using index/item number
问题描述
与此问题类似,当使用 Scripting.Dictionary
对象在VBA中,下面的代码的结果是意想不到的。
Similar to this issue, when using a Scripting.Dictionary
object in VBA, the outcome of the code below is unexpected.
Option Explicit
Sub test()
Dim d As Variant
Dim i As Integer
Dim s As String
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "a"
Debug.Print d.Count ' Prints '1' as expected
For i = 1 To d.Count
s = d.Item(i)
Debug.Print s ' Prints ' ' (null) instead of 'a'
Next i
Debug.Print d.Count ' Prints '2' instead of '1'
End Sub
相同的结果实现:
For i = 0 To d.Count - 1
s = d.Item(i)
Debug.Print s
Next i
观看对象我实际上可以看到在它有两个项目,新添加的关键是 1
,从 i
添加。如果我将此循环增加到更高的数字,那么字典中的项目数量会增加,每次循环一次。
Watching the object, I can actually see that it has two items, the key for the newly added is 1
, as added from i
. If I increase this loop to a higher number, then the number of items in the dictionary is increased, once for each loop.
我已经在Office / VBA 2003年,2010年和2013年。都表现出相同的行为,我期望其他版本(2007)也将。
我可以解决这与其他循环方法,但是当我尝试存储对象时,我抓住了我的防守,并且在 s = d.Item(i)上获得了一个对象预期错误 / code>行。
I can work around this with other looping methods, but this caught me off guard when I was trying to store objects and was getting an object expected error on the s = d.Item(i)
line.
为了纪录,我知道我可以这样做:
For the record, I know that I can do things like this:
For Each v In d.Keys
Set o = d.item(v)
Next v
但是我更好奇为什么我似乎无法通过数字迭代项目。
But I'm more curious about why I can't seem to iterate through the items by number.
推荐答案
根据文档的项目
属性:
设置或返回Dictionary对象中指定键的项目。
Sets or returns an item for a specified key in a Dictionary object.
在你的情况下,你没有一个项目的密钥是 1
这样做:
In your case, you don't have an item whose key is 1
so doing:
s = d.Item(i)
实际上创建一个新的您的字典中的键/值对,值为空,因为您没有使用可选的 newItem
参数。
actually creates a new key / value pair in your dictionary, and the value is empty because you have not used the optional newItem
argument.
该词典还具有 项目
方法允许循环遍历索引:
The Dictionary also has the Items
method which allows looping over the indices:
a = d.Items
For i = 0 To d.Count - 1
s = a(i)
Next i
这篇关于通过使用索引/项目编号的Scripting.Dictionary循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!