简体   繁体   中英

Excel VBA WorksheetFunction VLookup multiple range search - is it possible?

I use check boxes on individual worksheets to set ranges for performing VLookup functions. One of the check boxes needs to set two distinct ranges in which to search. I'm out of ideas on how to make this work. All the other possible variants are searching a continuous string of cells (ie [S9:T20] or [S55:T66] but not both. If I end up having to u multiple variables and perform the function twice the rest of my code will probably not work. Any ideas would be appreciated including if some sort of Find function might do similar work. Below are snippets of the code that I use:

  Dim rngO As Variant

  ElseIf ActiveSheet.Shapes("Check Box 43").ControlFormat.Value = 1 Then
   rngO = [S9:T20;S55:T66]

The rngO variant is used as shown below (one example):

Case 2
With ActiveSheet
.Range("U2").Value = "1Y"
.Range("V2").Value = WorksheetFunction.VLookup("1Y", rngO, 2, False)
.Range("U3").Value = "1P"
.Range("V3").Value = WorksheetFunction.VLookup("1P", rngO, 2, False)
.Range("U4").Value = "."
.Range("V4").Value = "."

short answer: Yes - it is!

longer answer:

You wrap the WorksheetFunction.VLookup() by some code looking at each area of your source range individually.

Function MyVLookup(Arg As Variant, Source As Range, ColNum As Integer, Optional CmpSwitch As Boolean = True) As Variant
Dim Idx As Integer

    MyVLookup = CVErr(xlErrNA)                     ' default return value if nothing found
    On Error Resume Next                           ' trap 1004 error if Arg is not found

    For Idx = 1 To Source.Areas.Count
        MyVLookup = WorksheetFunction.VLookup(Arg, Source.Areas(Idx), ColNum, CmpSwitch)
        If Not IsError(MyVLookup) Then Exit For    ' stop after 1st match
    Next Idx

End Function

and in your original code replace all calls to WorksheetFunction.VLookup() by calls to MyVLookup() with the same parameters.

Alternatively you can use this function directly in a cell formula (that's what I usually do with it ...)

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