我知道如何使用match和index在excel中执行此操作。我的电子表格有很多这些查找,但必须易于审核。
在纯excel公式中,它很简单:
=index(match()...match()) of the table
虽然容易做到但是如果表的大小发生变化等,会产生很大的麻烦。公式的可读性也很差。表格以及标题和列的命名范围使得进行故障排除变得更加困难。
Col1 Col2 Col3
Row1 1 2 3
Row2 4 5 6
Row3 7 8 9
我命名此范围,行和列名称分别为第一行和第一行。
因此Excel变量将被称为test_table。
想写一个我可以调用的VBA函数:
=VBAlookup("Row2", "Col2", test_table)
returns 5
我正在使用python与DataNitro和pandas轻松地进行拼接。不擅长VBA,所以在VBA写这篇文章会花费很长时间。当然,我不是第一个或只是寻找这个功能,但谷歌搜索似乎没有让我到任何地方。
不想回答我自己的问题,但到目前为止我的解决方案(改编自@John Bustos'以下答案)是:
Public Function VBAlookup(RowName As Variant, ColName As Variant, Table As Range) As Variant
Dim RowNum As Integer
Dim ColNum As Integer
VBAlookup = "Not Found"
For RowNum = 1 To Table.Rows.Count
If Table.Cells(RowNum, 1) = RowName Then
For ColNum = 1 To Table.Columns.Count
If Table.Cells(1, ColNum) = ColName Then
VBAlookup = Table.Cells(RowNum, ColNum)
End If
Next ColNum
End If
Next RowNum
End Function
这会以正确的格式获取任何类型的内容,如果值不在表格中,也会提供一些反馈
答案 0 :(得分:2)
这应该这样做:
Public Function VBAlookup(RowName As String, ColName As String, Table As Range) As String
Dim RowNum As Integer
Dim ColNum As Integer
VBAlookup = ""
For RowNum = 1 To Table.Rows.Count
If Table.Cells(RowNum, 1).Text = RowName Then
For ColNum = 1 To Table.Columns.Count
If Table.Cells(1, ColNum).Text = ColName Then
VBAlookup = Table.Cells(RowNum, ColNum).Text
End If
Next ColNum
End If
Next RowNum
End Function
请注意,我没有进行任何错误检查等,这是不错的做法!