2017-01-18 3 views
1

いくつかの項目で辞書を作成し、すべてのキーについてさまざまな項目を合計する必要があります。excel-vba - 辞書項目をループ内で合計することはできません

しかし、私はできません。私はいくつかのコメントでコードを投稿します。私は

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 
+0

をするだけ..あなたrealize'Range( "XX1")不思議COLUMN'は '戻ります。細胞(1,648)。カラム。したがって、カラム648。 –

+0

はい、説明を簡単にするために偽の名前を挿入しました。私がdict(pk)(1)+ attr(1)をイミディエイトウィンドウに入力すると、正しい値が返されます。私は正しい値をdict(pk)(1) – NG83

答えて

1

よりDETAを追加する必要がある場合、次のように私は行くだろう知ってみましょう:。

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 
+0

opに渡すことができない理由を理解していません: 'dictionary(Key)'の値を変更すると、キーが自動的に追加されます。だから、If Then Elseの必要はありません。 –

+0

@ NG83あなたはそれを通過しましたか? – user3598756

+0

ご協力いただきありがとうございます。私はまだそれに取り組んでいます。私はこの解決策を私の問題に適合させることができず、私はクラスを最初に使ってから、そのクラスで辞書を使うことを考えています – NG83

関連する問題