Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

Sub alternateFunctionForCountIF()

Dim DS As Worksheet
Set DS = ThisWorkbook.ActiveSheet

Dim lcol As Integer


lcol = DS.Cells(1, Columns.Count).End(xlToLeft).Column
Dim fieldHeader As String

Dim lrow As Long, i As Long, j As Long


Dim countifCol As Integer, fieldCol As Integer

fieldHeader = InputBox("Enter the column header to apply COUNTIF")


If Len(fieldHeader) = 0 Then
MsgBox ("Invalid input. " & Chr(13) & "Please enter the column header text
and try again")
Exit Sub
End If
For i = 1 To lcol
If fieldHeader = DS.Cells(1, i).Value Then
fieldCol = i
Exit For
End If
Next i
If fieldCol = 0 Then
MsgBox (fieldHeader & " could not be found among the headers. Please enter
a valid column header")
Exit Sub
End If

countifCol = fieldCol + 1
lrow = DS.Cells(Rows.Count, "A").End(xlUp).Row
DS.Range(DS.Cells(1, countifCol).EntireColumn, DS.Cells(1,
countifCol).EntireColumn).Insert
DS.Cells(1, countifCol) = fieldHeader & "_count"

DS.Sort.SortFields.Clear
DS.Sort.SortFields.Add Key:=Range(DS.Cells(2, fieldCol), DS.Cells(lrow,
fieldCol)), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With DS.Sort
.SetRange Range(DS.Cells(1, 1), DS.Cells(lrow, lcol))
.header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With

Dim startPos As Long, endPos As Long


Dim checkText As String
For i = 2 To lrow
checkText = LCase(CStr(DS.Cells(i, fieldCol).Value))

If (checkText <> LCase(CStr(DS.Cells(i - 1, fieldCol).Value))) Then


startPos = i
End If
If (checkText <> LCase(CStr(DS.Cells(i + 1, fieldCol).Value))) Then
endPos = i
For j = startPos To endPos
DS.Cells(j, countifCol) = endPos - startPos + 1
Next j
End If
Next i
MsgBox ("Done")
End Sub

Alt+F11

You might also like