VBA - count substrings in string

iknowu99

Well-known Member
Joined
Dec 26, 2004
Messages
1,158
Office Version
  1. 2016
Good day all, here is the goal:

string="ABBBBACCC"
goal=2 'number of occurances of "A"


Instead of going letter by letter (for looping), I am looking for a function to do this. THankS
 

Excel Facts

Copy a format multiple times
Select a formatted range. Double-click the Format Painter (left side of Home tab). You can paste formatting multiple times. Esc to stop
Hi iknowu99

Try:

Code:
MsgBox Len(string) - Len(Replace(string, "A", ""))

Hope this helps
PGC
 
Upvote 0
I know this is extremely long after the original post, but I want to share with everyone a very fast way to do this since it has had a good impact in my programs' speed.

VBA Code:
Sub TestSpeedOfSubStringOccurences()
Dim T As Double, S As String, X As Long, L As Long, LngPos As Long
S = "ABBBBACCC"
Const SubString As String = "A"
T = Timer
For L = 0 To 10000000
    X = Len(S) - Len(Replace$(S, SubString, vbNullString, 1, -1, vbBinaryCompare))
Next L
MsgBox "Replace Function: " & Timer - T
T = Timer
For L = 0 To 10000000
    LngPos = 1
    X = 0
    Do

        LngPos = InStrB(LngPos, S, SubString, vbBinaryCompare)
        If LngPos > 0 Then
            X = X + 1
            LngPos = LngPos + 1
        End If
       
    Loop Until LngPos = 0
Next L
MsgBox "InStrB Function: " & Timer - T
End Sub
 
Upvote 0
Here is another way:

Code:
Dim S as String
S = "ABBBBACCC"
MsgBox "count = " & UBound(Split(S, "A"))
 
Last edited:
Upvote 0

Forum statistics

Threads
1,223,929
Messages
6,175,451
Members
452,643
Latest member
gjcase

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top