我正在尝试做一个excel,该excel计算某个字母在表格列中出现的次数。
我想做的是创建一个动态表,在其中我可以随时添加新行。因此,我需要一个以列之一为参数的函数,该函数计算另一个参数出现的次数。
例如,计算“列”(:
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
这里的问题是函数找不到表,但是表存在。 我究竟做错了什么? 是 ActiveSheet.ListObjects(“ foo”)。ListColumns(column).range.Select 吗? 这不是范围吗?我无法在函数中访问它吗?
谢谢。
答案 0 :(得分:0)
你不能只是使用
=COUNTIF(foo[[#All],[Column1]],"A")
否则,
我将传递ListObject名称和列标题与搜索值一起进行搜索,并在函数中使用Countif返回计数。您还可以更改功能以将工作表作为参数传递给功能,以使其更加灵活。
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
数据: