Excel MAXIFfunction还是仿真?

我在Excel中有一个中等大小的数据集,我希望从中提取B列中值的最大值,但那些只对应于列A中符合特定条件的单元格。

所需的function类似于SUMIFCOUNTIF ,但都不需要那些返回的数据。 没有MAXIFfunction; 我该如何效仿?

您可以使用数组公式。在要计算最大值的单元格中input:= Max(If([test],[if true],[if false])用方括号中的值replacetesting,如果返回true,返回如果返回false,例如:

 =MAX(IF(MOD(A2:A25,2)=0,A2:A25,0) 

在这个公式中,如果除以2的值没有余数,则返回A列中的值。 请注意,我在比较中使用了一系列单元格,如果是假而不是单个单元格,则使用该值。

现在,在编辑单元格的同时,按Ctrl + Shift + Enter键(同时按住Ctrl键和Shift键,然后按回车键)。

这将创build一个数组公式,对该范围中的每个值起作用。

编辑顺便说一句,你想要做这个程序化或手动? 如果以编程方式,那么你使用的是什么环境? VBA? C#?

编辑如果通过VBA,您需要使用FormulaArray属性和R1C1引用,如下所示:

 Range("A1").Select Selection.FormulaArray = "=MAX(IF(MOD(R[1]C:R[24]C,2)=0,R[1]C:R[24]C,0))" 

当你想使用dynamic或命名的范围时,数组公式不能很好地工作(例如,“当前行上面具有与当前行相同的行的最大行数)”如果你不想使用一个数组公式,你可以总是诉诸VBA做这样的事情:

 Function maxIfs(maxRange As Range, criteriaRange As Range, criterion As Variant) As Variant maxIfs = Empty For i = 1 To maxRange.Cells.Count If criteriaRange.Cells(i).Value = criterion Then If maxIfs = Empty Then maxIfs = maxRange.Cells(i).Value Else maxIfs = Application.WorksheetFunction.Max(maxIfs, maxRange.Cells(i).Value) End If End If Next End Function 

到目前为止提供的代码的一个限制是,你被限制在2个条件。 我决定进一步采取这个代码来限制MaxIfs函数的条件数量。 请看这里的代码:

  Function MaxIfs(MaxRange As Range, ParamArray Criteria() As Variant) As Variant Dim n As Long Dim i As Long Dim c As Long Dim f As Boolean Dim w() As Long Dim k As Long Dim z As Variant 'Error if less than 1 criteria On Error GoTo ErrHandler n = UBound(Criteria) If n < 1 Then 'too few criteria GoTo ErrHandler End If 'Define k k = 0 'Loop through cells of max range For i = 1 To MaxRange.Count 'Start by assuming there is a match f = True 'Loop through conditions For c = 0 To n - 1 Step 2 'Does cell in criteria range match condition? If Criteria(c).Cells(i).Value <> Criteria(c + 1) Then f = False End If Next c 'Define z z = MaxRange 'Were all criteria satisfied? If f Then k = k + 1 ReDim Preserve w(k) w(k) = z(i, 1) End If Next i MaxIfs = Application.Max(w) Exit Function ErrHandler: MaxIfs = CVErr(xlErrValue) End Function 

此代码允许1到多个条件。

此代码是根据Hans V在Eileen's Lounge上发布的多个代码开发的。

快乐的编码

DIEDRICH