VBA count number of periods

gailb
3StarLounger
Posts: 254
Joined: 09 May 2020, 14:00

VBA count number of periods

Post by gailb »

I have a long text string and want to count the number of periods in the first part. I'm using the Split to separate the first part to count the periods.

I get A1.1. and I'd like to show the count of two periods as I'm going to apply some format around the cells that have a certain number of periods.

MyCnt returns 0

Code: Select all

Sub CountPeriod()
    Dim i As Long
    Dim LastRow As Long: LastRow = Range("A" & Rows.Count).End(xlUp).Row
    Dim MyText As String
    Dim MyCnt As Long
    For i = 1 To LastRow
        MyText = Split(Range("A" & i), " ")(0)
        MyCnt = WorksheetFunction.CountIf(Range("A" & i), ".")
    Next i
End Sub

User avatar
HansV
Administrator
Posts: 78412
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: VBA count number of periods

Post by HansV »

The COUNTIF function returns the number of cells in a range that satisfies a certain condition; you cannot use it to count characters within a single string.
Use this instead:

Code: Select all

        MyCnt = Len(MyText) - Len(Replace(MyText, ".", ""))
Best wishes,
Hans

gailb
3StarLounger
Posts: 254
Joined: 09 May 2020, 14:00

Re: VBA count number of periods

Post by gailb »

Thanks again Hans. As I continued my search, I found this which also works well.

Code: Select all

MyCnt = UBound(Split(Split(Range("A" & i), " ")(0), "."))