PonyEars
PonyEars

Reputation: 2254

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.

Upvotes: 0

Views: 2971

Answers (1)

Tim Williams
Tim Williams

Reputation: 166615

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

Upvotes: 2

Related Questions