命名单元格的值 table

Value of cell in named table

如何使用可读公式(即 rows/cells 通过名称而非索引引用的公式)获取命名 table 中特定单元格的值?

上图中我想显示tableFinancials单元格(Income, Feb)的值。我可以使用什么语法?

正如我提到的,您可以使用用户定义的函数来隐藏复杂性,例如

Public Function Financials(month As String, item As String) As String

'Object to represent the table    
Dim lo As ListObject: Set lo = Range("Table1").ListObject

'Integers to act as coordinates    
Dim x As Integer, y As Integer

'Find the column
x = lo.HeaderRowRange.Find(month).Column - lo.HeaderRowRange.Column + 1

'Find the row
y = lo.DataBodyRange.Columns(1).Find(item).Row - lo.HeaderRowRange.Row

' Return the value at the coordinates x,y
Financials = lo.DataBodyRange(y, x).Value

End Function

(使用工作簿中 table 的名称更新 Range("Table1").ListObject,或者您可以向函数添加另一个参数)

然后您可以在工作簿单元格中调用此函数,例如本示例

=Financials("Feb", "Profit")

我很难相信微软没有竭尽全力为其客户提供解决方案!

从@maxhob17 那里得到启发,这是一个通用的解决方案,可以与名为 table:

any 一起使用
Public Function TLookup(tablename As String, key As String, col As String)
    'From a table, find the corresponding value for a key (in the first column)

    'Object to represent the table
    Dim lo As ListObject: Set lo = range(tablename).ListObject

    'Integers to act as coordinates
    Dim x As Integer, y As Integer

    'Find the column
    x = lo.HeaderRowRange.Find(col).column - lo.HeaderRowRange.column + 1

    'Use the key to find the row
    y = lo.DataBodyRange.Columns(1).Find(key).Row - lo.HeaderRowRange.Row

    ' Return the value at the coordinates x,y
    TLookup = lo.DataBodyRange(y, x).Value

End Function

In the VB Window, insert the code above in a module. Remember to save your Excel file in xlsm format.

那么您应该能够在 table 中插入以下公式:

=TLookup("Financials", "Feb", "Profit")

这个技巧将改变我的生活;它可能会改变你的。 它再简单不过了,不是吗?

I also documented this solution in github.