如何在MyVlookup函数中使用通配符?

时间:2013-12-09 17:44:20

标签: excel-vba vba excel

使用 = MyVlookup(B1,Sheet1!A:A,1)在Excel中调用以下函数时,我得到了我想要的内容。

  

函数MyVlookup(Lval As Range,c As Range,oset As Long)As Variant

     
    

Dim cl As Range
    对于每个cl in c.Columns(1).Cells
    如果UCase(Lval)= UCase(cl)则为     MyVlookup = cl.Offset(,oset - 1)
    退出功能
    结束如果
    接下来
    结束功能

  

但是我想在 B1 周围使用通配符,例如的 “*” &安培; B1&安培; “*”即可。当我这样做时,我得到一个错误(#ARG!)。我尝试使用双引号,但它也没有用。我该怎么做才能克服这个问题?

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

尝试以下代码

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

开头的字符串
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

结尾的字符串
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

包含

的字符串
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