VBA code for SUMIFS?

后端 未结 3 1564
眼角桃花
眼角桃花 2020-12-22 02:34

I\'m trying to write a custom function that will let me retrieve a cell from the first row in a range that meets x number of criteria. I imagine this would be very similar t

3条回答
  •  攒了一身酷
    2020-12-22 02:55

    IMHO ADO is not suitable for use in excel worksheet functions (poor performance and cannot easily be used on the worksheet containing the data). here is a VBA alternative:

    
    Function MFind(theRange As Range, ParamArray Tests() As Variant) As Variant
    '
    ' Parameters are:
    ' The Range to be searched
    ' the values to be searched for in successive columns
    ' all search values except the last use =
    ' the last search value uses >=
    ' the function returns the value from the last column in the range
    '
        Dim vArr As Variant
        Dim j As Long
        Dim k As Long
        Dim nParams As Long
        Dim blFound As Boolean

    vArr = theRange.Value2
    nParams = UBound(Tests) - LBound(Tests) + 1
    If nParams >= UBound(vArr, 2) Then
        MFind = CVErr(xlErrValue)
        Exit Function
    End If
    
    For j = 1 To UBound(vArr)
        blFound = True
        For k = LBound(Tests) To nParams - 2
            If vArr(j, k + 1) <> Tests(k) Then
                blFound = False
                Exit For
            End If
        Next k
        If blFound Then
            If vArr(j, nParams) >= Tests(nParams - 1) Then
                MFind = vArr(j, UBound(vArr, 2))
                Exit For
            End If
        End If
    Next j
    

    End Function

提交回复
热议问题