所有键的值都相同(VBA)
我有一本字典,每把钥匙都是数字0-7。每个项目都是两个数值的集合。对于我遍历的数据集中的每个值,代码检查它属于哪个键1-7,从字典中提取适当的集合,将数据添加到集合中,然后将集合插入字典中。它还将每个值添加到字典中的0键,以便在最后0键将包含一个总计,即输出应如下所示:所有键的值都相同(VBA),vba,excel,Vba,Excel,我有一本字典,每把钥匙都是数字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:10
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
问题是,当我在完成所有这些之后检查字典时,每个集合都包含相同的值!即使我在此范围内进行调试,zero subtotalColl
fromregDict(0)
也包含我刚刚放回regDict(thisRegion)
的“新”值作为subtotalColl
非常感谢您的帮助
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!