我有一个字典,其中每个键的编号为0-7。每个项目都是两个数字值的集合。对于我正在迭代的数据集中的每个值,代码检查它所属的键1-7,从字典中提取适当的集合,将数据添加到集合中,然后将集合插回到字典中。它还将每个值添加到字典中的0键,以便最后0键将包含总计,即输出应如下所示:
Key:Value
0:100
1:20
2:10
3:10
4:20
5:10
6:5
7:25
我遇到的问题是输出类似于: 键:值
0:100
1:100
2:100
3:100
4:100
5:100
6:100
7:100
似乎每次我使用密钥从字典中提取集合时,无论密钥如何都会拉出相同的集合,然后将数据添加到该集合中。
字典:
For region = 0 To 7
regDict.Add region, blankColl
Next region
添加项目:
thisRegion = 'some number 1-7 found elsewhere
' pull the collection from the regDict
Set subtotalColl = regDict.Item(thisRegion)
subtotalSales = subtotalColl("Item") + thisSales
subtotalColl.Remove ("Item")
subtotalColl.Add Item:=subtotalSales, Key:="Item"
' replace the collection for thisRegion with the new one
regDict.Remove thisRegion
regDict.Add thisRegion, subtotalColl
' ----------- "region 0" gets every record no matter
' ----------- what the region of the record is
' pull the collection at 0 from the regDict
Set zeroSubtotalColl = regDict.Item(0)
subtotalSales = zeroSubtotalColl("Item") + thisSales
zeroSubtotalColl.Remove ("Item")
zeroSubtotalColl.Add Item:=subtotalSales, Key:="Item"
' replace the collection for Region 0 with the new one
regDict.Remove 0
regDict.Add 0, zeroSubtotalColl
问题在于,在完成所有这些操作后检查字典时,每个集合都包含相同的值!即使我在此内进行调试,zeroSubtotalColl
中的regDict(0)
也包含我刚刚将regDict(thisRegion)
作为subtotalColl
放回的“新”值。
任何帮助非常感谢。
答案 0 :(得分:0)
blankColl
始终是对同一个集合的引用,并为每个键添加它,因此所有"值"指向同一个对象。
电流:
Set regdict = CreateObject("scripting.dictionary")
Set blankColl = New Collection 'guessing here what you did...
For region = 0 To 7
regdict.Add region, blankColl
Next region
regdict(1).Add "hello"
Debug.Print regdict(7).Count '>>1 oops - should be empty!
修正:
For region = 0 To 7
regdict.Add region, New Collection
Next region
regdict(1).Add "hello"
Debug.Print regdict(7).Count '>>0 still empty!