如何将表名传递给Excel中的函数

我在Excel中有各种设置表,每个都有两个列标题Parameter和Value。

我想传递一个特定的表名到一个getParameter函数,该函数在表中查找一个特定的参数名,返回相关的参数值,并执行所有的error handling,例如下面的代码段:

 Function getParameter(.... ... Dim paramterValue as Variant With Application parameterValue = .Index([tableName[Value], .Match("parameterName", [tableName[Parameter], 0)) If Not IsError(parameterValue) then ... Else ... End If End With End Function 

我如何定义适当的函数参数并调用函数?

VBA表可select为ListObject对象 。 但是这些对象只在工作表范围内。 所以我们必须知道放置表的工作表才能使用wrksht.ListObjects(tableName)来获取它。

为了更加灵活,我们可以使用Evaluate来评估结构化引用:

 Public Function getParameter(tableName As String, parameterName As Variant) as Variant Dim parameterValue As Variant Dim oRangeTValues As Range Dim oRangeTParameters As Range Set oRangeTValues = Evaluate("" & tableName & "[Value]") Set oRangeTParameters = Evaluate("" & tableName & "[Parameter]") With Application parameterValue = .Index(oRangeTValues, .Match(parameterName, oRangeTParameters, 0)) If Not IsError(parameterValue) Then getParameter = parameterValue Else getParameter = CStr(parameterValue) End If End With End Function 

这将在所有工作表上使用,因为表名在实际工作簿范围内。

这应该被用作用户定义的函数,使用单元格公式如=getParameter("TableName","Parameter")

我会这样尝试,确定表格和对应于你的TableName的ListObject:

 Function getParameter(ByVal tableName As String, ByVal parameterName As String) As Variant Dim parameterValue As Variant Dim RgVal As Range Dim wS As Worksheet Dim LOTable As ListObject Application.Volatile Set wS = Evaluate(tableName).Parent Set LOTable = wS.ListObjects(tableName) Set RgVal = LOTable.DataBodyRange With Application.WorksheetFunction parameterValue = .Index(RgVal.Columns(2), .Match(parameterName, RgVal.Columns(1), 0)) End With 'Application.WorksheetFunction If Not IsError(parameterValue) Then getParameter = parameterValue Else '... DoEvents getParameter = CStr(parameterValue) End If End Function 

在VBA中调用:

 Sub test_GetParameter() Debug.Print getParameter("Table1", "testParam") End Sub 

在Excel中调用:

 = getParameter("Table1", "testParam") 

@ R3uk阿克塞尔·里克特的代码是足够的,但你的也可以。