简体   繁体   English

在vba中以数组形式使用表(索引,匹配,vlookup函数)

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

Trying to create function in vba to perform a index match function. 尝试在vba中创建函数以执行索引匹配功能。 I am referencing a excel table, and I want to reference the headers, not column number. 我正在引用一个excel表,并且我想引用标题而不是列号。 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. 当我将此功能放入VBA时,无法使阵列正常工作。 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. 您可以通过其标题引用ListColumn ,然后使用其Index属性。

If your lookup value is in C4 and the column name is in C5 , then try something like this: 如果您的查找值在C4 ,列名在C5 ,请尝试执行以下操作:

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: 样本表和数据:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM