简体   繁体   中英

How do i use a table as input to a function in Excel vba?

I have a function that i would like to make more general. But i can't get the last part of the function to work as input to the function.

how do i use tables as input to a funktion? I would like to break out the table name and use it as input so i can use the function in other contexts.

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

can i make this with a string some how?

The tables exist as named ranges, you can access these directly with .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

And you could also pass the heading instead of the number:

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

如果要避免使用UDF,可以使用此工作表公式

=SUMPRODUCT(HOUR(Table1[Hours]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM