简体   繁体   中英

Excel VBA - Sum rows/columns in a 2D array

Let's say that we have a 4x5 array. How can I sum get a separate 1D array with 5 elements where every element represents the column-sum of elements from the first array?

If done in the spreadsheet

I think I understand your question. At the bottom of each column simply put a SUM equation and sum over only the numbers in that column. For example if your array is in A1:E4 (first five columns and first four rows) put the following in cell A5:

=SUM(A1:A4)

And then copy cell A5 into cells B5 to E5.

EDIT - If done in VBA

Dim Arr_1(1 to 4, 1 to 5) as Double
Dim Arr_2(1 to 5) as Double
For col = 1 to 5
    Arr_2(col) = 0
    for row = 1 to 4
        Arr_2(col) = Arr_2(col) + Arr_1(row, col)
    Next row
Next col
Dim Arr_1(1 to 4, 1 to 5) as Double
Dim Arr_2(1 to 5) as Double
For col = 1 to 5
    Arr_2(col) = 0
    for row = 1 to 4
        Arr_2(col) = Arr_2(col) + Arr_1(row, col)
    Next row
Next col

Thank you, user1228123!

The code sums the column of YourArray; for sum of the row switch 0 and 1

 With Application.WorksheetFunction
       sum_array = .sum(.Index(YourArray(), 0, 1)) 'switch 0 and 1 for row
    End With

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