Excel:如果满足另一列(也是多个)中的条件,则对每行中的多列值求和

Excel:如果满足另一列(也是多个)中的条件,则对每行中的多列值求和

请参阅所附图片,其中包含与实际工作簿类似的示例表:

示例表

我想在 BD 列中编写公式,以便根据类型为每个客户添加评级。例如,对于客户 Ava,我希望公式生成以下内容:B 列(类型 A)下的 22,因为她的行中所有类型均为 A,评级分别为 7、8 和 7(7 加 8 加 7 等于 22)。如果在行中未找到类型(在此示例中为类型 B 和 C),则 C 列和 D 列(分别为类型 B 和 C)中的结果为 0。“类型、名称、代码和评级”列将向右延伸(以涵盖每月),并在它们之间有其他列。

我尝试过嵌套 if、vlookups、sumif、索引匹配等,但尚未找到适合长期使用的正确公式组合,因为“类型、名称、代码和评级”的新列组不断添加。每次添加这些列的新组时,我创建的公式都需要更新。

答案1

单元格 B2 的公式

=SUM((($E2:$XFA2)=B$1)*IFERROR(VALUE($H2:$XFD2),0))

这实际上是“矩阵公式”(需要通过 CTRL+SHIFT+ENTER 确认)确认后将此单元格拉伸至 B、C、D 列。

此公式发现“评级”列始终位于“类型”列右边 3 列。

答案2

这可以满足您的要求,而且可以扩展!不过它是用 VBa 编写的。我知道您要求使用工作表函数,但因为您没有合适的答案,所以我提供这个。

请记住,没有撤消,因此请确保先备份文件。

Option Explicit    
Sub WalkThePlank()

Dim startRow As Integer
startRow = 2                     'update this if needed Cap'ain, assumes content starts on row 2 as your "headings" be on row 1. Argggghhhh

Dim startCol As Integer
startCol = 69                   '69 is for Column E, the first column you want to look at. If this be wrong, then I'll feed myself to the sharks

Dim currentCol As Integer    
Dim typeToUse As String        
Do While Range("A" & startRow).Value <> ""
currentCol = startCol    
Do While Range(Chr(currentCol) & 1).Value <> ""
    Dim heading As String
    heading = Range(Chr(currentCol) & 1).Value        
    If (LCase(heading) = "type") Then
        typeToUse = Range(Chr(currentCol) & startRow).Value
    End If        
    If (LCase(heading) = "ranking") Then
        If LCase(typeToUse) = "a" Then
            Range("B" & startRow).Value = Range("B" & startRow).Value + Range(Chr(currentCol) & startRow).Value
        End If
        If LCase(typeToUse) = "b" Then
            Range("C" & startRow).Value = Range("C" & startRow).Value + Range(Chr(currentCol) & startRow).Value
        End If
        If LCase(typeToUse) = "c" Then
            Range("D" & startRow).Value = Range("D" & startRow).Value + Range(Chr(currentCol) & startRow).Value
        End If
    End If
    currentCol = currentCol + 1
Loop    
startRow = startRow + 1
Loop    
End Sub

如何在 MS Office 中添加 VBA?

唯一的标准是,从左到右,类型列必须位于排名之前。

在您的屏幕截图中,您有 4 列的“组”

类型 名称 代码 评级

有了上述这些,你可以拥有 2 人或 20 人的团队!它仍然有效

如果你在数据的最右侧添加一组额外的列,无论是 2、3、4 组(如你所见)还是其他任何数字,它仍然可以工作

在此处输入图片描述

运行 VBa 后

在此处输入图片描述

然后删除 TypeA、TypeB 和 TypeC 列中的值并添加另外 2 列(我省略了所调用的列Argh以显示不同的结构并不重要)

在此处输入图片描述

并运行完全相同的 VBa

在此处输入图片描述

相关内容