How to count number of words in a given string
Posted on January 5, 2009
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | 'String Manipulation - How to count number of words in a given string 'How to create a list of each word, and how many times it appears in the source string. Option Explicit Public Function WORD_COUNT(ByVal StringToCount As String) As String Dim WordsToCount As Variant Dim intIndex As Integer Dim ScanCount As Integer Dim CurrentWord As String Dim WordCount As Integer Dim FinishedText As String WordCount = 0 WordsToCount = Split(StringToCount, chr ( 32)) Debug.Print "Total No. of words: " & UBound(WordsToCount) - LBound(WordsToCount) For intIndex = 0 To UBound(WordsToCount) CurrentWord = WordsToCount(intIndex) WordCount = 1 For ScanCount = 0 To UBound(WordsToCount) If ScanCount <> intIndex Then If WordsToCount(ScanCount) = CurrentWord Then WordCount = WordCount + 1 End If End If Next If InStrRev(FinishedText, CurrentWord & "(" & WordCount & ")") = 0 Then FinishedText = FinishedText & CurrentWord & "(" & WordCount & ")" & vbCrLf End If Next WORD_COUNT = FinishedText End Function |