字典数组包含所有数组元素的相同字典引用
问题描述:
我有一个数组,并在一个while循环内,我将一行数据插入字典中,然后将每个字典添加到数组中。字典数组包含所有数组元素的相同字典引用
我的设置是这样的:
while something
Dim MyDict as new Scripting.Dictionary
MyDict.RemoveAll
'Add data
MyDict.add "something","something"
If Count = 0 Then
ReDim MyArray(0)
Else
ReDim Preserve MyArray(UBound(MyArray, 1) + 1)
End If
'Add the dictionary to the array of dictionaries
Set MyArray(UBound(MyArray, 1)) = MyDict
wend
然而,在while循环的结束点字典全阵列相同的dictionary-最后一个。我认为通过在while循环中声明字典并使用New,以及removeall我会避免这种情况....
如何确保每个字典不仅仅是插入最后一个字典的引用?
答
这是Kovags告诉你:
Dim MyDict as Scripting.Dictionary
while something
Set MyDict = new Scripting.Dictionary
'Add data
MyDict.add "something","something"
If Count = 0 Then
ReDim MyArray(0)
Else
ReDim Preserve MyArray(UBound(MyArray, 1) + 1)
End If
'Add the dictionary to the array of dictionaries
Set MyArray(UBound(MyArray, 1)) = MyDict
wend
...虽然我想你可能会发现它更容易使用的集合为这个insted的数组。
我不明白你想要达到的目标。 您是否试过在循环中声明MyDic outsite while循环,然后在循环中执行“Set MyDic = new Scripting.Dictionary”? – Kovags
Kovags是正确的,没有'Set'你有一个数组有n个元素保持对同一个字典实例的引用。 –