简体   繁体   中英

Excel UDF for VLOOKUP(MATCH()) that uses structured table references

I'm trying to build an Excel user defined function VLOOKUP_NAME(value, table, column_name) that would implement:

VLOOKUP(value, table, MATCH(column_name, table[#Headers], FALSE), FALSE)

How do I do this in VBA? VBA doesn't seem to accept structured references like table[#Headers] .

Also, I'd be interested in knowing about the performance consequences of implementing this as a UDF as well.

Also, the reason I'm doing this is to replace a ton of ugly formulas with more readable formulas. Other better suggestions to achieve this are welcome.

I'm not familiar with that structured reference syntax, but have you tried constructing the formula and using the worksheet Evaluate() method?

Here's a simple example:

Function TestEval(s1 As String, s2 As String)
    TestEval = Application.Caller.Parent.Evaluate(s1 & "/" & s2)
End Function

EDIT: After checking out the whole structured table thing, this seems to work:

Function TableLookup(val, tbl As Range, colName As String)
    Dim indx, rv
    indx = Application.Match(colName, tbl.Rows(1).Offset(-1, 0), 0)

    If Not IsError(indx) Then
        rv = Application.VLookup(val, tbl, indx, False)
        TableLookup = IIf(IsError(rv), "Not found", rv)
    Else
        TableLookup = "Col??"
    End If
End Function

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