简体   繁体   中英

Using tables in as arrays in vba, (index,match,vlookup functions)

Trying to create function in vba to perform a index match function. I am referencing a excel table, and I want to reference the headers, not column number. Below is the worksheet that I have created and works.

=VLOOKUP(C4, Table2, MATCH(C5,Table2[#Headers],0), 0)

When I put this function into VBA, I am having trouble making the array work. I think...

MATCH(C5,Table2[#Headers],0)

needs to start with codes like this below.

ActiveSheet.ListObjects("Table2").ListColumns ("d") 
ActiveSheet.ListObject("Table2[d]")

You can refer to a ListColumn by its header, and then use its Index property.

If your lookup value is in C4 and the column name is in C5 , then try something like this:

Sub Test()

    With Sheet1
        Dim myTbl As ListObject
        Set myTbl = .ListObjects("Table2")

        Dim indx As Integer
        indx = myTbl.ListColumns(.Range("C5").Value).Index

        Dim result As Variant
        result = Application.VLookup(.Range("C4").Value, myTbl.Range, indx, 0)

        MsgBox result
    End With

End Sub

Sample table and data:

在此处输入图片说明

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