2017-07-27 58 views
1

這個問題有點複雜(我覺得),所以我會盡我所能來解釋這個問題。Column Summation Excel VBA

本質上,我想要做的是向下移動範圍中的每列,向上添加每個單元格值(獲取列的總和),然後將其添加到數組中。但是,當測試數組中保存的值時,它始終爲0.是否有更好的方法來執行此操作?

這裏是我當前的代碼:

Dim sumHoldings(1 To 36) As Double 
k = 1 

For Each rep In repNames 

    If rep <> vbNullString Then 
    Worksheets(rep).Activate 
    Dim i As Integer 
    Dim sumHolder As Double 

    For i = 3 To 6 

     Columns(i).Select 

     For Each rangeCell In Selection 

      If rangeCell <> vbNullString Then 

       sumHolder = rangeCell.Value + sumHolder 

       Else: 
        sumHoldings(k) = sumHolder 'this current method will keep overwriting itself 
        k = k + 1 
        Exit For 

      End If 

     Next rangeCell 
    Next i 
    End If 
Next rep 

繼承人的什麼,我試圖做一個直觀表示: enter image description here

enter image description here

任何幫助是極大的讚賞,謝謝!

回答

2

這就是你需要做的。

Option Explicit 

Public Sub TestMe() 

    Dim myRng  As Range 
    Dim myCell  As Range 
    Dim myCol  As Range 
    Dim arrResults As Variant 
    Dim dblSum  As Double 
    Dim lngCounter As Long 


    Set myRng = Range("R17:T25") 
    ReDim arrResults(myRng.Columns.Count -1) 

    For Each myCol In myRng.Columns 
     dblSum = 0 
     For Each myCell In myCol.Cells 
      dblSum = dblSum + myCell 
     Next myCell 
     arrResults(lngCounter) = dblSum 
     lngCounter = lngCounter + 1 
    Next myCol 

End Sub 

數組arrResults會得到每列的總和。確保編輯Set myRng = Range("R17:T25")對你有意義。

該代碼的工作原理與您所描述的完全相同 - 它使用範圍中的每列,使用myRng.Columns並對它進行迭代。然後它需要myCol.Cells中的每個單元格,並重新進行迭代。因此,複雜性是O2

+0

'dblSum = dblSum + myCell.Value' –

+0

@RafaelMatos - '不需要.Value',它的工作原理W/O它。 – Vityata

+0

我沒有測試代碼,但如果你這麼說,那沒關係。 –

0

你得到零的原因是你的if語句讓它們在你的數組中沒有任何內容時將空單元存儲到你的數組中。只是移動存儲部分,畢竟細胞總結:

For Each rangeCell In Selection 

If rangeCell <> vbNullString Then 

sumHolder = rangeCell.Value + sumHolder 

End If 

Next rangeCell 
    sumHoldings(k) = sumHolder 
    k = k + 1 
Next i 
End If