如何合并VBA Dictionary中的重复条目并汇总对应值
修复VBA Dictionary重复条目并汇总值的方案
原代码的问题
- 没必要用Collection存储值:直接把数值作为字典的Item即可,汇总操作会更简洁
- 变量名笔误:
ColumnDKey是错误写法,应该是ColumnAKey - 逻辑错误:当键已存在时,不是添加新的汇总条目,而是要更新原有键对应的数值,原代码反而会生成新的重复项
修正后的代码
Dim dict As Object Set dict = CreateObject("scripting.dictionary") Dim i As Long Dim ColumnAKey As Variant Dim ColumnBValue As Variant ' 遍历数据,合并重复键并求和 For i = 1 To 6 ColumnAKey = Worksheets("Sheet1").Cells(i, "A").Value ColumnBValue = Worksheets("Sheet1").Cells(i, "B").Value If Not dict.Exists(ColumnAKey) Then ' 键不存在时,直接添加键和对应值 dict.Add ColumnAKey, ColumnBValue Else ' 键已存在时,累加数值 dict(ColumnAKey) = dict(ColumnAKey) + ColumnBValue End If Next i ' 输出结果到立即窗口 For Each ColumnAKey In dict.Keys Debug.Print ColumnAKey & " - " & dict(ColumnAKey) Next
代码说明
- 用字典Item直接存储数值,避免Collection带来的冗余操作
- 键存在时直接累加对应数值,确保每个键仅对应一个汇总后的值
- 最终输出时,每个键只会打印一次,对应合并后的结果
内容的提问来源于stack exchange,提问作者Jrules80
相关产品推荐
相关产品推荐

