简体   繁体   English

如何使用表格作为Excel vba中函数的输入?

[英]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.

相关问题 如何正确使用 Excel VBA 中的 Like 函数? - How do I use the Like Function in Excel VBA properly? 我如何在VBA编辑器中使用Excel功能 - how do I use a excel function inside the vba editor 如何在 Excel VBA 中使用间接 Function 将方程合并到 VBA 宏 Function - How do I use the Indirect Function in Excel VBA to incorporate the equations in a VBA Macro Function 在Excel中使用VBA IsEmpty函数时,如何检查用户输入? - How do I check for user input when using the VBA IsEmpty function in Excel? 在Excel VBA中,如何更改作为用户输入传递给函数的单元格区域 - In Excel VBA, How do I change the cell range that was passed as a user input to a function 如何使用 VBA 在 Excel 中展平数据在行之间拆分的表格? - How do I use VBA to flatten a table in Excel where data is split between rows? 使用值过滤时,如何在Excel VBA数据透视表中使用变量? - How do I use a variable in Excel VBA pivot table when using value filtering? 如何为每个VBA Excel将inputbox输入分配给变量 - How do I assign inputbox input to variable for each vba excel 如何在 VBA 中使用 Excel 的内置模函数 (MOD)? - How do I use Excel's built-in modulo function (MOD) in VBA? 如何在表格的2列中突出显示所有重复项? (Vba,Excel) - How do i highlight all duplicates in 2 columns of a table? (Vba, excel)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM