JHS
JHS

Reputation: 35

Excel VBA Cumulative sums in arrays

Visual Representation of the arrays

Hi,

I just started with Excel VBA and I'm working on a little project with arrays. The data in Array1 is static. I'm looking for a way to fill Array2 using VBA.

For each cell in Array2 I’d like to do the following:

Array2(Row1) = Array1(Row1)

….

Array2(Row 3) = Array1(Row1+Row2+Row3)

….

Array2(Row5) = Array1(Row1+Row2+….+Row5)

How can I translate this operation to VBA?

Upvotes: 0

Views: 474

Answers (1)

SJR
SJR

Reputation: 23081

Have you tried anything? Here is one approach.

Sub x()

Dim array1, array2() As Long, i As Long, j As Long, k As Long

array1 = Range("A1").CurrentRegion.Value 'array1 populated from sheet, but could be via code

ReDim array2(1 To UBound(array1, 1), 1 To UBound(array1, 2))

For i = LBound(array1, 1) To UBound(array1, 1)
    k = k + 1
    For j = LBound(array1, 2) To UBound(array1, 2)
        array2(i, j) = Application.Sum(Application.Index(array1, Evaluate("ROW(1:" & k & ")"), j))
    Next j
Next i

Range("I1").Resize(UBound(array2, 1), UBound(array2, 2)).Value = array2

End Sub

Upvotes: 1

Related Questions