1

我有一个想要更通用的功能。但我无法让函数的最后一部分作为函数的输入。

我如何使用表格作为功能的输入?我想分解表名并将其用作输入,以便我可以在其他上下文中使用该函数。

Function GetTotalHours("Tablename?" As ??, columnNumber As Integer) As Integer

    For Each Row In [Tablename].Rows

        getTotalHours = getTotalHours + DateTime.Hour(Row.Columns(columnNumber).Value)

    Next

End Function

我可以用一个字符串来做这个吗?

4

2 回答 2

2

这些表以命名范围的形式存在,您可以使用 直接访问它们.Range(name)

Function GetTotalHours(tableName As String, columnNumber As Integer) As Integer
    Dim r As Range
    Dim c As Range

    Set r = ActiveSheet.Range(tableName).Columns(columnNumber)
    For Each c In r.Cells
        GetTotalHours = GetTotalHours + DateTime.Hour(c.Value)
    Next
End Function

您还可以传递标题而不是数字:

Function GetTotalHoursByHeading(tableName As String, columnName As String) As Integer
    Dim r As Range
    Dim c As Range

    Set r = ActiveSheet.Range(tableName & "[" & columnName & "]")
    For Each c In r.Cells
        GetTotalHoursByHeading = GetTotalHoursByHeading + DateTime.Hour(c.Value)
    Next
End Function
于 2013-10-20T11:05:00.503 回答
1

如果你想避免 UDF,你可以使用这个工作表公式

=SUMPRODUCT(HOUR(Table1[Hours]))
于 2013-10-20T16:27:34.677 回答