简体   繁体   English

以动态表格栏为参数的Excel vba函数

[英]Excel vba function with dynamic table column as parameter

I'm trying to do an excel that counts the number of times that a certain letter appears in a table column. 我正在尝试做一个excel,该excel计算某个字母在表格列中出现的次数。

What I'm trying to do is to create a dynamic table, in which i can always add new lines. 我想做的是创建一个动态表,可以随时在其中添加新行。 Because of that, i need a function that has as a parameter one of the columns, which counts the number of times that another parameter appears. 因此,我需要一个以列之一为参数的函数,该函数计算另一个参数出现的次数。

Example, count the number of "shift" in the "column" (: 例如,计算“列”中的“班次”数(:

Function sumColumnShifts(column As Integer, shift As range) As Integer
    sumColumnShifts = sumDayShifts(ActiveSheet.ListObjects("foo").ListColumns(column).range.Select, shift)
End Function

Public Function sumDayShifts(ByVal Target As range, shift As range) As Variant
    Dim res As Integer
    res = 0
    For Each cell In Target    
        If shift.cells(1, 1).Value = cell.Value Then
            res = res + 1
        End If
    Next
    sumDayShifts = res
End Function

The problem here is the function can't find the table, but the table exists. 这里的问题是函数找不到表,但是表存在。 What am I doing wrong? 我究竟做错了什么? Is it the ActiveSheet.ListObjects("foo").ListColumns(column).range.Select ? ActiveSheet.ListObjects(“ foo”)。ListColumns(column).range.Select吗? This is not a range? 这不是范围吗? I can't access this in a function? 我无法在函数中访问它吗?

Thanks. 谢谢。

Can't you just use 你不能只用

=COUNTIF(foo[[#All],[Column1]],"A")

Otherwise, 除此以外,

I would pass the ListObject name and header of column to search along with the search value and use Countif in the function to return the count. 我将传递ListObject名称和列标题与搜索值一起搜索,并在函数中使用Countif返回计数。 You could also alter the function to pass the worksheet as an argument to the function to make it more flexible. 您还可以更改函数以将工作表作为参数传递给函数,以使其更加灵活。

Option Explicit   
Public Sub Test()

    Const SEARCH_HEADER As String = "Column1"
    Const SEARCH_VALUE As String = "A"
    Const TABLE_NAME As String = "foo"

    Debug.Print GetCount("foo", SEARCH_HEADER, SEARCH_VALUE)
End Sub

Public Function GetCount(ByVal tableName As String, ByVal searchHeader As String, ByVal searchValue As String) As Variant
    Dim ws As Worksheet, table As ListObject
    Set ws = ThisWorkbook.Worksheets("Sheet1")
    On Error Resume Next
    Set table = ws.ListObjects("foo")
    On Error GoTo 0
    If table Is Nothing Or IsError(Application.Match(table.HeaderRowRange, searchHeader, 0)) Then
        GetCount = CVErr(xlErrNA)
        Exit Function
    End If

    GetCount = Application.WorksheetFunction.CountIf(table.ListColumns(searchHeader).DataBodyRange, searchValue)
End Function

Data: 数据:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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