Home » excel » excel – VBA: Sum the values in the row which are to left of reference

excel – VBA: Sum the values in the row which are to left of reference

Posted by: admin May 14, 2020 Leave a comment

Questions:

Say I have a 2-dimensional array. I want to sum the values in the row which are to the left of the current position (including current position).

Dim Arr As Variant
ReDim Arr(4,5)
Dim i As Integer
Dim j As integer
NumRows = UBound(V, 1)
NumCols = UBound(V, 2)

For j = 0 to NumCols
    For i = 0 to Num Rows 
        Arr(i,j) = ......
    Next i
Next j 

Is there an equivalent to SUM(X:Y), where I can reference an element in the array?

I think this, for example, would sum the third row:

With Application.WorksheetFunction
   dSum = .Sum(.Index(Arr, 3, 0))
End With

but I need to sum to the left the of position, including the current position.

If my array is 2×4:

[1,1,2,3]
[1,1,3,5]

it would be:

[1,2,4,7]
[1,2,5,10] 
How to&Answers:

I think this basically does what you want. I have populated an array from the sheet to make things quicker, and placed the sums into a second array of the same dimensions.

Sub x()

Dim v, i As Long, j As Long, v2()

v = Range("A1:D2").Value
ReDim v2(1 To UBound(v, 1), 1 To UBound(v, 2))

For i = LBound(v, 1) To UBound(v, 1)
    For j = LBound(v, 2) To UBound(v, 2)
        v2(i, j) = Application.Sum(Application.Index(v, i, Evaluate("ROW(1:" & j & ")")))
    Next j
Next i

End Sub

enter image description here

This thread might be a useful read.