Function ModifiedCountif(ReferenceRange As Range, Criteria As Variant) As Long
Dim i As Long, k As Long, FirstRow As Long, LastRow As Long, FirstColumn As Long, LastColumn As Long
Dim StopPointRow As Long, StartPointRow As Long
Dim UsedCellsArray() As String, x As Long
Dim ws As Worksheet
If Len(Criteria) <= 255 Then
ModifiedCountif = Application.WorksheetFunction.CountIf(ReferenceRange, Criteria)
Exit Function
Else
FirstRow = FirstCellRow(ReferenceRange)
LastRow = LastCellRow(ReferenceRange)
FirstColumn = FirstCellColumn(ReferenceRange)
LastColumn = LastCellColumn(ReferenceRange)
'Initialise
Set ws = ReferenceRange.Worksheet
ModifiedCountif = 0
For i = FirstColumn To LastColumn
If Not IsEmpty(ws.Cells(LastRow, i)) Then
StopPointRow = LastRow
If Not IsEmpty(ws.Cells(LastRow - 1, i)) Then
StartPointRow = ws.Cells(LastRow, i).End(xlUp).Row
If StartPointRow < FirstRow Then
StartPointRow = FirstRow
End If
Else
StartPointRow = LastRow
End If
Else
StopPointRow = ws.Cells(LastRow, i).End(xlUp).Row
If StopPointRow < FirstRow Then
GoTo LEAVECURRENTCOLUMN
End If
If StopPointRow > 1 Then
If Not IsEmpty(ws.Cells(StopPointRow - 1, i)) Then
StartPointRow = ws.Cells(StopPointRow, i).End(xlUp).Row
If StartPointRow < FirstRow Then
StartPointRow = FirstRow
End If
Else
StartPointRow = StopPointRow
End If
Else
If Not IsEmpty(ws.Cells(StopPointRow, i)) Then
StartPointRow = StopPointRow
Else
GoTo LEAVECURRENTCOLUMN
End If
End If
End If
COUNTINGSTEP:
'Count
For k = StopPointRow To StartPointRow Step -1
If ws.Cells(k, i).Value = Criteria Then
ModifiedCountif = ModifiedCountif + 1
End If
Next k
If StartPointRow > FirstRow Then
StopPointRow = ws.Cells(StartPointRow, i).End(xlUp).Row
If StopPointRow < FirstRow Then
GoTo LEAVECURRENTCOLUMN
End If
If StopPointRow > 1 Then
If Not IsEmpty(ws.Cells(StopPointRow - 1, i)) Then
StartPointRow = ws.Cells(StopPointRow, i).End(xlUp).Row
If StartPointRow < FirstRow Then
StartPointRow = FirstRow
End If
Else
StartPointRow = StopPointRow
End If
Else
If Not IsEmpty(ws.Cells(StopPointRow, i)) Then
StartPointRow = StopPointRow
Else
GoTo LEAVECURRENTCOLUMN
End If
End If
Else
GoTo LEAVECURRENTCOLUMN
End If
If StartPointRow >= FirstRow Then
GoTo COUNTINGSTEP
End If
LEAVECURRENTCOLUMN:
Next i
End If
End Function