Excel MAXIF function or emulation?

前端 未结 3 741
陌清茗
陌清茗 2021-01-13 05:19

I have a moderately sized dataset in excel from which I wish to extract the maximum value of the values in Column B, but those that correspond only to cells in Column A that

3条回答
  •  情话喂你
    2021-01-13 05:27

    A limitation with the code provided thus far is that you are restricted to 2 conditions. I decided to take this code further to not restrict the number of conditions for the MaxIfs function. Please see the code here:

            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
    

    This code allows 1 to multiple conditions.

    This code was developed with reference to multiple code posted by Hans V over at Eileen's Lounge.

    Happy coding

    Diedrich

提交回复
热议问题