字典数组包含所有数组元素的相同字典引用



我有一个数组,在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循环结束时,整个字典数组都指向同一个字典——最后一个字典。我想通过在while循环中声明dictionary并使用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 

尽管我认为您可能会发现使用集合来代替数组更容易。

最新更新