Question

I have data as follows

SHEET 1:

A     B      
K01   0.5
K01   0.8
K02   0.6
K03   0.6
....

I need to get the lowest nearest value from col B, where I supply col A and the nearest (higher) value to match from col B.

For example: if the supplied values are var1 = 'K01' and var2 = '0.6' then the resulting formula should return row 1 in the example above.

I am stuck with how to get this formula done. Thanks.

Was it helpful?

Solution

Try this formula:

=MAX(IF(IF(A1:A4=E1,B1:B4)<=F1,IF(A1:A4=E1,B1:B4)))

with array entry (CTRL+SHIFT+ENTER).

enter image description here

As @barry houdini suggest in comments, you can simplify the formula:

=MAX(IF(A1:A4=E1,IF(B1:B4<=F1,B1:B4)))

with array entry.

OTHER TIPS

Since the lookup and match functions in Excel doesn't return arrays, I believe the best way to solve this problem would be to use a user function in VBA instead.

If you insert the following code in a module in VBA, it should make you able to return the value from column B as described in your question.

Function ReturnNearest(ColA As Range, ColB As Range, Var1 As Variant, Var2 As Variant)
    Dim LookupArr()
    Dim i As Integer, ArrCount As Integer
    ArrCount = 0

    'Fills array with all valid solutions
    For i = 1 To ColA.Rows.Count
        If ColA.Cells(i, 1).Value = Var1 Then
            If ColB.Cells(i, 1).Value <= Var2 Then
                ArrCount = ArrCount + 1
                ReDim Preserve LookupArr(1 To ArrCount)
                LookupArr(ArrCount) = ColB.Cells(i, 1).Value
            End If
        End If
    Next i

    'Finds the largest value of the possible solutions
    ReturnNearest = WorksheetFunction.Max(LookupArr)
End Function

Assuming you got your data in column A and B and your lookup values in cells E3 (Var1) and E4 (Var2), you can then use the following function to return the largest (nearest) value from column B based on the described criteria.

=ReturnNearest(A2:A5,B2:B5,E3,E4)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top