简体   繁体   中英

Excel VBA Lookup

Trying to use VBA in Excel to perform some VLookup equivalent function. I have this sample table:

在此处输入图片说明

Basically, this is what I want to do:

1) Based on the value in B12, lookup the value in table A1:A8. 2) Set cell B13 with the lookup returned value 3) If no match found (example, B12=100000), throw an error message.

I am currently using a bunch of "IF.. ElseIf" statements and it is becoming too cumbersome to maintain.

Thanks in advance.

You could just use formula at Cell B13:

=IF(B10>A8,"Error",INDEX($A$2:$B$8, SUMPRODUCT(--(A2:A8<=B10)),2))

That's for inclusive (ie Qty 1-9 belongs to level 1) based on the example you given.

Try this in the worksheet's private code sheet (right-click worksheet name tab, View Code.

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address(0, 0) = "B12" Then
        On Error GoTo meh
        Application.EnableEvents = False
        Dim m As Variant
        If IsNumeric(Target) Then
            If Target < 1 Or Target > Application.Max(Range("A2:A8")) Then
                Target.Offset(1, 0) = "out of range"
            Else
                m = Application.Match(Target, Range("A1:A8"))
                Target.Offset(1, 0) = Cells(m, "B").Value
            End If
        End If
    End If

meh:
    Application.EnableEvents = True

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM