将第 n 列中的每个单元格与动态行和列相加

问题描述 投票:0回答:2

我有一张包含可变数量的行和列的工作表。该表从四个标准列开始,然后是额外的八列组,具体取决于绘制报告的时间。

我需要将八个组中的第二、第三、第四和第五列单元格相加,以获得每行的第二、第三、第四和第五列单元格条目的总和。

我感觉我必须使用 Step 的循环将这些值添加到数组中。我很难概念化它。

arrays excel vba loops
2个回答
1
投票

假设您没有依赖 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))
    )
);

它的用法是这样的:

enter image description here

它需要三个参数:

  1. 行 - 即从标准四列中的第一列到最后一组 8 列的最后一列的数据

  2. 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"

  3. group_width - 在您的示例中,这是 8 - 但如果要更改,您可以在此处输入不同的数字

详细说明其工作原理:

让:

  • groups 是前四列之后的数据(使用 DROP 函数从行中删除前四列)
  • group_columns 是从 1 到 COLUMNS(groups) 的整数序列,它是 group_width 的倍数 - 在您的情况下是 8
  • group_indices 是每个组的从 1 到 group_width (8) 的整数

然后,将组中的数据乘以 group_indices 数组与position_to_sum 匹配的数组元素求和。

如果您不确定如何将此 lambda 函数添加到您的工作簿中,请安装 Excel Labs 和高级公式环境,然后将上面的代码粘贴到“模块”选项卡中:

enter image description here

点击“保存”后,您将能够像使用 Excel 中的任何其他函数一样使用该函数。


0
投票

你可以用VBA代码得到它。

  • 在您的情况下,不需要使用数组(aCol)来保留列索引,因为它是连续且连续的。它使代码对于其他项目更加灵活。即你必须用相同的逻辑得到第 1,4,5,8 列的结果。

Data samples

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
© www.soinside.com 2019 - 2024. All rights reserved.