2

title says it all... I want to find the most occurred char in a string and then count its occurences.

Example: IN: "aabbbbcccd" OUT: Most occurred: "b", 4 times.

I don't even need to know which char is, just the number of repeats. I want to do this using only Excel VBA.

I tried to look for some algorithm, I found some approaches like: Find the most occurrence of a character in string C#? but I don't know how to port to VBA, I am afraid that I can't :(

Thanks !

Community
  • 1
  • 1

2 Answers2

4

Here is one way to get the count of the most frequent character in a string.

Sub chCount()
    Dim str As String: str = "abldfeoslgsasasessasae"
    
    Dim Ruler As Variant
    Dim Counter As Long
    Dim lCount As Long
    Dim maxCount As Long
    
    lCount = Len(str)
    
    For ch = 1 To lCount
      Ruler = Split(str, Mid(str, ch, 1))
      Counter = UBound(Ruler)
      If maxCount < Counter Then
        maxCount = Counter
      End If
    Next ch
    
    msgbox(maxCount)

End Sub
miken32
  • 42,008
  • 16
  • 111
  • 154
Automate This
  • 30,726
  • 11
  • 60
  • 82
3

I know you want VBA but I can't resist a formula solution for anybody who might be interested or might want to convert to VBA.

With string in A1 use this "array formula" in another cell to get the count of the most frequent character in that string

=LEN(A1)-MIN(LEN(SUBSTITUTE(A1,MID(A1,ROW(INDIRECT("1:"&LEN(A1))),1),"")))

confirmed with CTRL+SHIFT+ENTER

barry houdini
  • 45,615
  • 8
  • 63
  • 81