1

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?

1

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

I still can't get this to work. Are you referring to a table as a sheet? because i mean i specific table on a sheet. not the entire sheet. like if i have a tale named trainingData on Sheet1.
Yes sorry, I really thought you mean tables = worksheets. I have edited the answer.
1

If you want to avoid a UDF, you could use this worksheet formula

=SUMPRODUCT(HOUR(Table1[Hours]))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.