Writing a VLOOKUP function in vba

前端 未结 6 1455
谎友^
谎友^ 2020-12-01 07:32

I\'m trying to lookup a value on a spreadsheet within a table array using the VLOOKUP function in my vba code. I don\'t know how to write it correctly.

Here is the

6条回答
  •  感情败类
    2020-12-01 08:09

    As Tim Williams suggested, using Application.VLookup will not throw an error if the lookup value is not found (unlike Application.WorksheetFunction.VLookup).

    If you want the lookup to return a default value when it fails to find a match, and to avoid hard-coding the column number -- an equivalent of IFERROR(VLOOKUP(what, where, COLUMNS(where), FALSE), default) in formulas, you could use the following function:

    Private Function VLookupVBA(what As Variant, lookupRng As Range, defaultValue As Variant) As Variant
        Dim rv As Variant: rv = Application.VLookup(what, lookupRng, lookupRng.Columns.Count, False)
        If IsError(rv) Then
            VLookupVBA = defaultValue
        Else
            VLookupVBA = rv
        End If
    End Function
    
    Public Sub UsageExample()
        MsgBox VLookupVBA("ValueToFind", ThisWorkbook.Sheets("ReferenceSheet").Range("A:D"), "Not found!")
    End Sub
    

提交回复
热议问题