简体   繁体   中英

Excel VBA Cumulative sums in 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM