excel-vba – 无法在循环中对字典项目进行求和

我创build一个包含一些项目的字典,我需要为每个项目添加各种项目。

但我不能。 我发表了一些评论的代码。 让我知道如果我必须添加更多的细节

Sub dict_sum() Dim dict as New Dictionary Dim i As Integer Dim pk As Variant dim attr as variant Dim attr_tmp As Variant For i = start_range To end_range 'loop on the column range pk = ObjO.Cells(i, ObjO.Range("primary_key").Column) 'set the primary key for the dictionary ReDim attr_tmp(1 To 4) 'read for the primary key cell the following for columns that contains numbers 'and obviously are on the same row of the primary key attr_tmp(1) = ObjO.Cells(i, ObjO.Range("xx1").Column) attr_tmp(2) = ObjO.Cells(i, ObjO.Range("xx2").Column) attr_tmp(3) = ObjO.Cells(i, ObjO.Range("xx3").Column) attr_tmp(4) = ObjO.Cells(i, ObjO.Range("xx4").Column) ReDim attr(1 To 1) 'with the following passage i'm trying to pass the sum of the previously columns to one variable 'that will be the item of the dictionary dict. attr(1) = attr_tmp(1) + attr_tmp(2) + attr_tmp(3) + attr_tmp(4) 'now if the key pk doesn't exists in the dictionary, it add the key(pk) and the item(attr(1)) to thedictionary 'with the else condition. 'If the key already exists, then add attr(1)to the key pk 'THE PROBLEMS IS IN THIS PASSAGE >> THE SUM DICT(PK)+ATTR(1) DOESN'T WORK AND EVERY TIME IT PASS ME THE VALUE OF ATTR(1) If dict.Exists(pk) Then dict(pk)(1) = dict(pk)(1) + attr(1) Else: dict.Add pk, attr Next i End Sub 

我会去如下:

 Option Explicit Sub dict_sum() Dim ObjO As Worksheet Dim dict As New Dictionary Dim i As Integer, start_range As Integer, end_range As Integer Dim pkC As Integer, xx1C As Integer, xx2C As Integer, xx3C As Integer, xx4C As Integer Dim attrSum As Double set ObjO = Workbooks("MyWorkbookName") '<--| adjust it to your needs start_range = 1 '<--| adjust it to your needs end_range = 100 '<--| adjust it to your needs With ObjO pkC = .Range("primary_key").Column xx1C = .Range("xx1").Column xx2C = .Range("xx2").Column xx3C = .Range("xx3").Column xx4C = .Range("xx4").Column For i = start_range To end_range 'loop on the column range attrSum = .Cells(i, xx1C) + .Cells(i, xx2C) + .Cells(i, xx3C) + .Cells(i, xx4C) dict.Item(.Cells(i, pkC)) = dict(.Cells(i, pkC)) + attrSum Next i End With End Sub