我有一张包含可变数量的行和列的工作表。该表从四个标准列开始,然后是额外的八列组,具体取决于绘制报告的时间。
我需要将八个组中的第二、第三、第四和第五列单元格相加,以获得每行的第二、第三、第四和第五列单元格条目的总和。
我感觉我必须使用 Step 的循环将这些值添加到数组中。我很难概念化它。
假设您没有依赖 VBA,这里有一个 lambda 函数可以完成您想要的操作:
SUMBYGROUPINDEX =LAMBDA(row, position_to_sum, group_width,
LET(
groups, DROP(row, , 4),
group_columns, SEQUENCE(1, COLUMNS(groups)),
group_indices, MOD(group_columns - 1, group_width) + 1,
SUMPRODUCT(groups * (group_indices = position_to_sum))
)
);
它的用法是这样的:
它需要三个参数:
行 - 即从标准四列中的第一列到最后一组 8 列的最后一列的数据
position_to_sum - 整数 <= 8 indicating which position within the groups of 8 you want to sum in this cell. In the example above, I've put the numbers 2, 3, 4 and 5 in the row above where the formulas are, so I can reference them. As shown, I'm using U$2 to say "Sum the 2nd columns from the groups"
group_width - 在您的示例中,这是 8 - 但如果要更改,您可以在此处输入不同的数字
详细说明其工作原理:
让:
然后,将组中的数据乘以 group_indices 数组与position_to_sum 匹配的数组元素求和。
如果您不确定如何将此 lambda 函数添加到您的工作簿中,请安装 Excel Labs 和高级公式环境,然后将上面的代码粘贴到“模块”选项卡中:
点击“保存”后,您将能够像使用 Excel 中的任何其他函数一样使用该函数。
你可以用VBA代码得到它。
Sub demo()
Dim arr, res(), aCol, i, j, k
Dim iRow As Long, iCol As Integer
arr = [a1].CurrentRegion.Value
iRow = UBound(arr)
iCol = UBound(arr, 2)
ReDim res(1 To iRow, 1 To 4)
aCol = Array(2, 3, 4, 5)
For j = 0 To UBound(aCol)
res(1, j + 1) = "SUM-COL" & aCol(j)
Next
For i = 2 To UBound(arr)
For j = 0 To UBound(aCol)
For k = 5 To iCol Step 8
res(i, j + 1) = res(i, j + 1) + arr(i, k + aCol(j) - 1)
Next
Next
Next
Cells(1, iCol + 2).Resize(iRow, 4).Value = res
End Sub