[英]Excel VBA - Sum rows/columns in a 2D array
假设我们有一个4x5的数组。 我如何求和得到一个包含5个元素的单独一维数组,其中每个元素代表第一个数组中元素的列和?
如果在电子表格中完成
我想我理解你的问题。 在每列的底部,只需简单地放入一个SUM方程,然后仅对该列中的数字求和。 例如,如果您的数组位于A1:E4(前五列和前四行)中,则将以下内容放入单元格A5中:
=SUM(A1:A4)
然后将单元格A5复制到单元格B5至E5。
编辑-如果在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
谢谢user1228123!
该代码对YourArray的列求和; 用于行开关0和1的总和
With Application.WorksheetFunction
sum_array = .sum(.Index(YourArray(), 0, 1)) 'switch 0 and 1 for row
End With
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.