Excel VBA函数在Cell范围内查找值

我知道如何使用匹配和索引在Excel中做到这一点。 我的电子表格有很多这些查找,但它必须很容易审计。

在纯粹的Excel公式中,它是一个简单的:

=index(match()...match()) of the table 

虽然容易做到这一点,如果桌子的大小发生变化,就会造成很大的负面影响。 公式的可读性也不好。 对表格和标题和列进行命名的范围使其更难以排除故障。

  Col1 Col2 Col3 Row1 1 2 3 Row2 4 5 6 Row3 7 8 9 

我将这个范围命名为行列名称分别作为第一行和第一列。

所以Excelvariables将被称为test_table。

想写一个我可以调用的VBA函数:

 =VBAlookup("Row2", "Col2", test_table) returns 5 

现在我正在用DataNitro和pandas来使用python来轻松地进行拼接。 不擅长VBA,因此在VBA中写这篇文章需要花很长时间。 当然,我不是第一个或只是寻找这个function,但谷歌search似乎没有让我到任何地方。

不想回答我自己的问题,但到目前为止我的解决scheme(改编自@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 

这会得到正确格式的任何types的内容,并且如果值不在表格中,则会给出一些反馈

这应该做到这一点:

 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 

请注意,我没有进行任何错误检查等,这将是一个很好的做法!