我对VBA很新 我有一个Excel范围的单元格将不断自动过滤,COUNTIFS UDF只考虑可见(过滤)单元格将对我有很大帮助。 我发现这个代码似乎是我需要的,但它只适用于COUNTIF,而不适用于COUNTIFS 如果有人对如何修改它以使其成为COUNTIFS有任何想法,那将是超级大的!
Function Vis(Rin As Range) As Range
'Returns the subset of Rin that is visible
Dim Cell As Range
Application.Volatile
Set Vis = Nothing
For Each Cell In Rin
If Not (Cell.EntireRow.Hidden Or Cell.EntireColumn.Hidden) Then
If Vis Is Nothing Then
Set Vis = Cell
Else
Set Vis = Union(Vis, Cell)
End If
End If
Next Cell
End Function
Function COUNTIFv(Rin As Range, Condition As Variant) As Long
'Same as Excel COUNTIF worksheet function, except does not count
'cells that are hidden
Dim A As Range
Dim Csum As Long
Csum = 0
For Each A In Vis(Rin).Areas
Csum = Csum + WorksheetFunction.CountIf(A, Condition)
Next A
COUNTIFv = Csum
End Function
答案 0 :(得分:0)
你可以做到这样做......
考虑到你有不同的范围来测试不同的条件:
Function COUNTIFSv(Rin1 As Range, Condition1 As Range, Optional Rin2 As Range, Optional Condition2 As Range, Optional Rin3 As Range, Optional Condition3 As Range) As Long
'Same as Excel COUNTIF worksheet function, except does not count
'cells that are hidden
Dim Csum As Long
Csum = 0
If Not IsMissing(Rin3) AND Not IsMissing(Condition3) Then
Csum = Csum + WorksheetFunction.CountIfs(Vis(Rin1),Condition1,Vis(Rin2),Condition2,Vis(Rin3),Condition3)
ElseIf Not IsMissing(Rin2) AND Not IsMissing(Condition2) Then
Csum = Csum + WorksheetFunction.CountIfs(Vis(Rin1),Condition1,Vis(Rin2),Condition2)
Else
Csum = Csum + WorksheetFunction.CountIfs(Vis(Rin1),Condition1)
End If
COUNTIFSv = Csum
End Function
或者您可以在不同条件下再次测试相同的范围:
Function COUNTIFSv(Rin As Range, Condition1 As Range, Optional Condition2 As Range, Optional Condition3 As Range) As Long
Dim Csum As Long
Csum = 0
If Not IsMissing(Condition3) Then
Csum = Csum + WorksheetFunction.CountIfs(Vis(Rin),Condition1,Vis(Rin),Condition2,Vis(Rin),Condition3)
ElseIf Not IsMissing(Condition2) Then
Csum = Csum + WorksheetFunction.CountIfs(Vis(Rin),Condition1,Vis(Rin),Condition2)
Else
Csum = Csum + WorksheetFunction.CountIfs(Vis(Rin),Condition1)
End If
COUNTIFSv = Csum
End Function