vbams-wordword-2007word-2003

Count all Comma In Selection or selected text


I want to count all Commas "," that occur only in selected text after that I will use Count as Integer to run the loop

My question is how do i Count , as following Image shows:

I Don't know how to use split and ubound. what is wrong with following code?

Sub CountComma()
Dim x As String, count As Integer, myRange As Range

Set myRange = ActiveDocument.Range(Selection.Range.Start, Selection.Range.End)

 x = Split(myRange, ",")
  count = UBound(x)

  Debug.Print count

End Sub

Solution

  • A simple split will work.

    x = Split("XXX,XXX,XXX,XXX,XX,XX", ",")
      Count = UBound(x)
      Debug.Print Count
    

    B/c the array starts at zero you can take to Ubound number as is.

    EDIT: To use a range .

    x = Split(Range("A1").Value, ",")
    

    To break down the code.

    Split("A string value","Delimiter to split the string by")
    

    And if you want a single line of code than,

    x = UBound(Split(myRange, ","))