[英]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)
. 这些表以命名范围存在,您可以使用.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]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.