Home > How-To Library > String Manipulation
How to count number of words in a given string
**************************************************************** * © 2007 CodeItBetter http://www.codeitbetter.com * * This notice MUST stay intact for legal use * **************************************************************** '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
If you would like to submit your code here please us. Do not forget to mention your name. We are always thankful to each and everyone of you who submitted their code here.