VBA 创建字典聚合值

VBA create dictionary aggregate values

我有六个变量,代表三对(key/value)。永远是三对。

cb1 = 1: cb1value = 10
cb2 = 1: cb2value = 20
cb3 = 8: cb3value = 10

我不擅长的是根据键聚合字典中的值。 所以在上述情况下,结果将是:

1, (10, 20)
8, (10)

这里的最终目标是使用 Sum(key) 来获得每个键的总数。

编辑:感谢您到目前为止的答复。也许我只是想得太复杂了。首先,我将所有值放在一个数组中,然后遍历它。

MyArray = Array(cb1, cb1value, cb2, cb2value, cb3, cb3value)

现在按键是每 2 步,所以在我的循环中:

For i = 0 To 5 Step 2
    If Not (keywords.Exists(MyArray(i))) Then
        keywords.Add MyArray(i), Collection(MyArray(i + 1))
    Else
        'If the key exists, the value should be added to the existing key's collection. **But how?**
    End If
Next i
For i = lbound(MyArray) To UBound(MyArray)-1 Step 2 
    If Not (keywords.Exists(MyArray(i))) Then keywords.Add MyArray(i), New Collection
    keywords(MyArray(i)).Add MyArray(i + 1)
Next i

获取集合中所有条目的总和:

Function SumCollection(col as Collection)
    Dim rv As Double, i
    For Each i in col
        rv = rv + i
    Next i
    SumCollection = rv
End Function

如果您只需要求和,则不需要集合:只需在添加每个项目时直接在字典中求和即可。