简体   繁体   中英

VBA Modify Excel COUNTIFS UDF

I'm very new to VBA I have an Excel range of cells that are going to be constantly auto-filtered and a COUNTIFS UDF that will only take into account only the visible (filtered) cells will help me greatly. I have found this code that seems to be what I need, but it only works for COUNTIF, and not for COUNTIFS If someone will has any ideas about how to modify it to make it COUNTIFS, would be supergreat!

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

You could achieve that doing something like this...

Considering that you have diferent ranges to test with diferent conditions:

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

OR You could test the same Range agains different conditions:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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