Home » excel » excel vba – How can I use wildcards with MyVlookup function?

excel vba – How can I use wildcards with MyVlookup function?

Posted by: admin May 14, 2020 Leave a comment

Questions:

When calling the below function in Excel by using =MyVlookup(B1,Sheet1!A:A,1) I get what I want.

Function MyVlookup(Lval As Range, c As Range, oset As Long) As Variant

Dim cl As Range

For Each cl In c.Columns(1).Cells

If UCase(Lval) = UCase(cl) Then

MyVlookup = cl.Offset(, oset – 1)

Exit Function

End If

Next

End Function

But I’d like to use wildcards around B1, e.g. “*”&B1&”*”. When I do that I get an error (#ARG!).
I tried using double quotation marks, but it didn’t work, either. What should I do to overcome this?

How to&Answers:

Try below code

Function MyVlookup(Lval As Range, c As Range, oset As Long) As Variant

    Dim cl As Range
    For Each cl In c.Columns(1).Cells
        If InStr(1, UCase(cl), UCase(Lval), vbTextCompare) > 0 Then
            MyVlookup = cl.Offset(, oset - 1)
            Exit Function
        End If
    Next
End Function

String beginning with

Function MyVlookup(Lval As Range, c As Range, oset As Long) As Variant

    Dim cl As Range
    For Each cl In c.Columns(1).Cells
        If cl Like Lval & "*" Then
            MyVlookup = cl.Offset(, oset - 1)
            Exit Function
        End If
    Next
End Function

string ending with

Function MyVlookup(Lval As Range, c As Range, oset As Long) As Variant

    Dim cl As Range
    For Each cl In c.Columns(1).Cells
        If cl Like "*" & Lval Then
            MyVlookup = cl.Offset(, oset - 1)
            Exit Function
        End If
    Next
End Function

string which contains

Function MyVlookup(Lval As Range, c As Range, oset As Long) As Variant

    Dim cl As Range
    For Each cl In c.Columns(1).Cells
        If cl Like "*" & Lval & "*" Then
            MyVlookup = cl.Offset(, oset - 1)
            Exit Function
        End If
    Next
End Function

Answer:

Function MyVlookup(Lval As String, c As Range, oset As Long) As Variant

Dim cl As Range

    Lval = UCase(Lval)

    For Each cl In c.Columns(1).Cells
        If UCase(cl) Like Lval Then
            MyVlookup = cl.Offset(, oset - 1)
            Exit Function
        End If
    Next
End Function