Excel 添加激发函数SumCellsByColor

Excel 添加激发函数SumCellsByColor,excel,vba,function,Excel,Vba,Function,谢谢你的论坛。我有一个关于现有代码的问题(不是我自己的)。代码本身可以很好地实现这个目的,但是现在我需要一些额外的代码,我不知道如何让它工作。下面可以看到原始代码 我需要函数能够有另一个条件。如果colmn D为true,我需要代码只能够在给定输入的情况下求和。类似于如果单元格(x;x)=“MJE”,那么… 我希望它有意义,否则请随意提问 Function SumCellsByColor(rData As Range, cellRefColor As Range) Dim indRefC

谢谢你的论坛。我有一个关于现有代码的问题(不是我自己的)。代码本身可以很好地实现这个目的,但是现在我需要一些额外的代码,我不知道如何让它工作。下面可以看到原始代码

我需要函数能够有另一个条件。如果colmn D为true,我需要代码只能够在给定输入的情况下求和。类似于如果单元格(x;x)=“MJE”,那么… 我希望它有意义,否则请随意提问

Function SumCellsByColor(rData As Range, cellRefColor As Range)
    Dim indRefColor As Long
    Dim cellCurrent As Range
    Dim sumRes

    Application.Volatile
    sumRes = 0
    indRefColor = cellRefColor.Cells(1, 1).Interior.Color
    For Each cellCurrent In rData
        If indRefColor = cellCurrent.Interior.Color Then
            sumRes = WorksheetFunction.Sum(cellCurrent, sumRes)
        End If
    Next cellCurrent

    SumCellsByColor = sumRes
End Function

有很多不同的方法,但我能想到的最简单的方法是:

Function SumCellsByColor(rData As Range, cellRefColor As Range, column_offset As Long, TextToMatch As String)
    Dim indRefColor As Long
    Dim cellCurrent As Range
    Dim sumRes

    Application.Volatile
    sumRes = 0
    indRefColor = cellRefColor.Cells(1, 1).Interior.Color
    For Each cellCurrent In rData
        If indRefColor = cellCurrent.Interior.Color And cellCurrent.Offset(0, column_offset).Value = TextToMatch Then
            sumRes = WorksheetFunction.Sum(cellCurrent, sumRes)
        End If
    Next cellCurrent

    SumCellsByColor = sumRes
End Function
然后,您可以在示例中使用以下命令调用它:

=SumCellsByColor(G$2:G$95;$C111,-3,"MJE")
其中,D列为G列左侧的3,即偏移量-3