Count the number of words in a textbox

Level:
Level1

Sometimes when entering text in an input field we want to know how many words we have entered. For example: Please provide a description of the damage (Maximum 500 words). It is easy to find out the number of characters entered in a text box, but to get the number of words using Visual Basic we need to put in a little more effort. The VB source code below demonstrates how we can do this.

To try out this source sample create a new VB6 program. Add a text box to the form and a command button. Double click the command button to get into its click event handler. Inside this method add the following code.

  1. Dim Counter As Integer
  2. Dim StartPos As Integer
  3.  
  4. If Trim(Text1) = "" Then
  5.     NumOfWords = 0
  6.     Exit Sub
  7. End If
  8.  
  9. Text1 = Trim(Text1) ' Remove All Spaces
  10.  
  11. While InStr(1, Text1, " ") > 0 'Remove Double Spaces
  12.     StartPos = InStr(1, Text1, " ")
  13.     Text1 = Mid(Text1, 1, StartPos - 1) & _
  14.                 Mid(Text1, StartPos + 1, Len(Text1) - StartPos)
  15. Wend
  16.  
  17. NumOfWords = 1
  18. For Counter = 1 To Len(Text1)
  19.         If Mid(Text1, Counter, 1) = " " Then
  20.                 NumOfWords = NumOfWords + 1
  21.         End If
  22. Next Counter
  23.  
  24. MsgBox "Found " & NumOfWords & " Words"

Once you have added your code run the application and enter some text in the text box. Click the button and you should see a message box that tells you exactly how many words you have entered.

Note: The source for this was found at DreamVB which is no longer online.

If you enjoyed this post, subscribe for updates (it's free)

don't count space and display only chharacter of number in wor

example- THE SUN
3 + 3 = 6
TOTAL 6 CHHARACTER+ 1 SPACE= 7-1SPACE=6CHHARACTER

hello every one

WHY every one try to remove two spaces what if there 3 or 4 spaces, no need to remove multi-space from string to count words, most close code to correct is Mr. kevnar code, and here is the right way to do it (no space removing required):

You need 1 TextBox named Text1 and 1 CommandButton named Command1

Private Sub Command1_Click()
Dim str As String
Dim cnt As Long
str=Split(Text1.Text," ")
cnt=0
For i=LBound(str) to UBound(str)
If Len(Trim(str(i)))<>0 Then cnt=cnt+1
Next i
MsgBox cnt & " word(s) found"
End Sub

as simple as this ;)

WHY not this ?

Len(Trim$(Text1.Text))

why cant u use this one ..
and if u want to ignore spaces then
just use ...if else count them and subtract from the above method .. ?

it doesnt work

it doesnt work

Try Mine (CountWords)

Function CountWords(ByVal uString As String) As Long
'By John Gilbert M. C.
sLen = Len(uString)
xString = Trim(uString): If xString = "" Then Exit Function
For cID = 1 To sLen
xCH = Mid(xString, cID, 1)
If cID = 1 And xCH <> " " Then wCnt = wCnt + 1
If xCH = " " Then
While xCH = " " And cID <= sLen
cID = cID + 1
xCH = Mid(xString, cID, 1)
Wend
wCnt = wCnt + 1
End If
Next cID
CountWords = wCnt
End Function

problem

i have problem in this code, i want to reverse the contents of the text box. plz help me... :(((

" carray = Textbox1.Text.ToCharArray()
reverse = String.Empty

For i As Integer = 0 To carray.Length - 1 & i >= -1
i -= 1
reverse += carray(i)
Next
TextBox2.Text = reverse"

textbox

hi
i want change the style of sub selection text in text box to bold and iralic or change its font .how can i do it ? for example i wrote "hello to all" in the text box . i want select "to" and then by pressing a command1 i want change its style to bold or change its font. how can i do that ?

thank you very much and goodbye

Word count in a textbox

Private Function WordCount(countme As String) As Integer
Dim words() As String

countme = Replace(countme, " ", " ")
words() = Split(countme, " ")
WordCount = UBound(words) + 1
End Function

Private Sub Text1_Change()
Label1.Caption = WordCount(Text1.Text) & " words found."
End Sub

How to count words with multiline

I need a code that counts the number of words in a textbox that exclude spaces and the enter character
Pls. Help me :'(

No. of words in the supplied sentence

Dim word, a As String
Dim b, i, count As Byte
word = txtsentence.Text
a = word.Trim
b = a.Length
count = 0
For i = 0 To (b - 1)
If a.Substring(i, 1) <> " " Then
count = count + 1
End If

Next
lblnow.Text = count

count the first and the last word in a string vb

I would like to know how can I count the first and the last word in a text box.

vb features

whether we can create a focus for a single button alone among various buttons & which will be enabled & accessed by enter key & mouse. Similar to accept button of vb.net

request for a code to count the number of alphabets and words

i am new in vb learning i need such a code which would b able to count the total number of all words and alphabets with their detail in in table or some other good form, for example if i write "well come to my home" now when i execute tht code this code should tell me tht total words =5, welcome=1, to =1, my=1, home=1, and also tell me abt all letters e.g, w=1,e=3,l=1,c=1 and so on, if any body could help me and send me such a code, it will b a very pleasent thing for me and for all vb lovers..........................thanks my email is koolpinkguy@yahoo.com.au if any body has such code can sen me on this address

hi...

bro we have the same problem.. xD
if someone already gave you the code would you mind on sharing it? :D

I look forward to your response for this message.
Thank you.

HELLO!!!!!!!!!!

HELLO!!!!!!!!!!

Easy Way

Public function WordCount(data As String) as long
dim newdata as string
dim arrdata() as string
dim space as string
dim ilen as long
space = " "
newdata = trim(data)
While InStr(1, newdata, space & space ) > 0 'two spaces
newdata = replace(trim(data), space & space , space ) 'replace two spaces with a space
wend
if len(trim(newdata)) = 0 then
WordCount=0
else
arrdata()=split(newdata, space)
ilen = ubound(arrdata(), 1)
WordCount=ilen + 1 'account for zero based array
end if
end function

Updated Easy Way

'also fix trim issue
newdata = trim(replace(trim(data), space & space , space )) 'replace two spaces with a space

Updated Easy Way

after line
newdata = trim(data)
'remove line breaks
newdata = replace(replace(replace(newline, vbcrlf, space), vblf, space), vbcr, space)
'remove punctuation
newdata = replace(replace(replace(newdata,".",space),"?",space),"!",space)
newdata = replace(replace(replace(newdata,",",space),";",space),":",space)

Count Number of Words in a String Very Easy (update)

'okay here am i again please disregard my first submission because what i had in mind is when the first char in the string is a space. it works fine when a space is at the beginning. now i recode to count at the first char of the string whether it be a space or not. this is very basic for beginners to understand.

Private Sub Command1_Click()
Dim WordCount As Integer
Dim ChrCount As Integer

For ChrCount = 1 To Len(Text1.Text)
If Mid(Text1.Text, ChrCount, 1) = " " Then GoTo skip_Count ' just don't count when a space is met
If ChrCount <> 1 Then 'to check if the cursor is in the first char then check for space
If Mid(Text1.Text, ChrCount - 1, 1) = " " Then 'just counts when a previous char is a space (this is the trick)
WordCount = WordCount + 1
End If
Else
WordCount = WordCount + 1 'counts initially if first char is not equal to space
End If

skip_Count:

Next

MsgBox "Number of words found = " & WordCount
End Sub

Count No Of Words from paragraph/text

Hi Dude,
This code will take few time to calculate the number of words from given text,

Dim intCount As Integer
intCount = 1
For i = 1 To Len(Text1.Text)
If Mid(Text1.Text, i, 1) = " " Then
intCount = intCount + 1
End If
Next
MsgBox intCount & " Words Found"

Please have a look, in case of any issue please feel free to revert back
Deepak Shitole
s.deepak150@gmail.com

Count Words

try typing more spaces between words (example: "The<&space>quick<&space><&space><&space>brown<&space><&space>fox.") . we know that the sentence has only four words.... your code returns 7

Count Number of Words in a String Very Easy

'count number of words in a string disregarding number of spaces in between or at the beginning/start of the string. no more trimming off the spaces because the problem of all the other codes here is when there are more spaces in between the words.

Private Sub Command1_Click()
Dim WordCount As Integer
Dim ChrCount As Integer
For ChrCount = 1 To Len(Text1.Text)
If Mid(Text1.Text, ChrCount, 1) = " " Then GoTo skip_Count ' just don't count when a space is met
If Mid(Text1.Text, ChrCount - 1, 1) = " " Then 'just counts when a previous char is a space (this is the trick)
WordCount = WordCount + 1
End If
skip_Count:
Next
MsgBox "Number of words found = " & WordCount 'was it great!
End Sub

'hope this helps....

just add error trapping... in case the first letter is not blank

'not for multiline textbox

Private Sub Command1_Click()
On Error Resume Next ' add this line
Dim WordCount As Integer
Dim ChrCount As Integer
For ChrCount = 1 To Len(Text1.Text)
If Mid(Text1.Text, ChrCount, 1) = " " Then GoTo skip_Count
If Mid(Text1.Text, ChrCount - 1, 1) = " " Then
WordCount = WordCount + 1
End If
skip_Count:
Next
MsgBox "Number of words found = " & WordCount
End Sub

This code is faster and very easy to understand anyone.

Hi All VB Readers,
'Please have a very easy solution to count words from given textbox/paragraph

Dim bulCounted As Boolean
Dim intcounter As Integer
bulCounted = False
intcounter = 1
TextBox1.Text = Trim(TextBox1.Text)
For i = 1 To Len(TextBox1.Text)
bulCounted = False
If Mid(TextBox1.Text, i, 1) = " " Then
For j = i To Len(TextBox1.Text)
If Mid(TextBox1.Text, j, 1) <> " " Then
intcounter = intcounter + 1
i = j
bulCounted = True
GoTo x
End If
Next
x:
If bulCounted = False Then
intcounter = intcounter + 1
End If
End If
Next
MsgBox "Above text box contains " & intcounter & " words", vbInformation

Thanks & Regards
Deepak Shitole
s.deepak150@gmail.com

search for a word in a textbox

Hi,

I need to count how many time a particular word comes in a sentence.

Ex: If i type " How are you? I am doing Fine. How did u reach office today? " in text box Text1.txt

I want to count the number of occurrences the word "How" come in the above sentence.

I have used the code below:

Dim Total3 As Integer
Dim Index3 As Integer
Dim OIndex3

Index3 = 1

While Index3 >= OIndex3

Index3 = InStr(Index3, Text1.Text, "How") + 1

If Index3 > OIndex3 Then
Total3 = Total3 + 1
OIndex3 = Index3
End If

Wend

But the problem is if the count is Zero the while loop is going in to a infinite loop.... Please help.

Check this code it is also working fine

c = 0
g = Len(intext)

Function new_conv(intext As String)

c = 0
g = Len(intext)

For i = 1 To g
If Mid(intext, i, 1) = " " Then
c = c + 1
End If
''this line for checking two spaces
'If Mid(intext, i, 1) = " " Then i = i + 2
While Mid(intext, i, 1) = " "
i = i + 1
Wend

Next

MsgBox "no of word in textbox is" & c + 1

End Function

find number of words in a text box

''Please ignore my two Previos recent solution which has some spelling mistake

Private Sub command1_click()
c = 0
For i = 1 To Len(Text1.Text)
If Mid(Text1.Text, i, 1) = " " Then
c = c + 1
End If
''this line for checking two spaces
If Mid(Text1, i, 1) = " " Then i = i + 2
Next
MsgBox "no of word in textbox is" & c + 1
End Sub

One Advice

Hi,

If we gives more than one space between two words then this code is not working properly.

Thanks & Regards
Deepak Shitole

I would like to how to write a frequency distrbution progam

I would like to know how to write a program in visual basic that counts the number of times a number is entered.

Count the number of words in a textbox

I have tested then code for the task, but it did not work!
In line 11 and 12 i had to change the search-string to 2 spaces to find the double spaces.
Then it worked OK for a normal textbox, but when counting a 100 or 200 kB file it was VERY slow.

I have made new code for removing double spaces. In my text there was a lot of spaces - for indenting tekst - and I had to remove all of them. I also made new code for the counting task. This made the word counting MUCH faster:

Chars   Words    Original  My solution
 35 k    3798       3,7 s      0,015 s 
 70 k    7595      15,0 s      0,016 s
100 k   11392      33,7 s      0,031 s
200 k   22783     138,2 s      0,063 s

My code is:

Public Sub WordCounting(Text0 As String)
 1. Dim NumOfWords As Integer, WCount() As String
 2. Dim Text1 As String
 3.     
 4.     Text1 = Text0
 5.     If Trim(Text1) = "" Then        'Text1 is empty
 6.         NumOfWords = 0
 7.         Exit Sub
 8.     End If
 9.      
10.     Text1 = Trim(Text1)             'Remove All Spaces at start and end
11.      
12.     While InStr(1, Text1, "  ") > 0 'Remove >1 Spaces
13.         Text1 = Replace(Text1, "  ", " ")
14.     Wend
15.      
16.     WCount = Split(Text1, " ")
17.     NumOfWords = UBound(WCount) + 1
End Sub

sorry sir this code may b

sorry sir this code may b workin on ur system but when i tried this code this didnt work at all. some lines of this code i think 11 and twelve r declared an error by compiler and at the end of this code the compler also indicates some problem, and when i executed this code i mean when i clicked the button nothin happened so i suggest u sir to re write or check whre the problem is, and if u could b able to write such a code which would b able to ( count all words and letters and also show the detail of repetition of each word and letter) in any document or file or even in a huge book, if u could write plz post me on this address. koolpinkguy@yahoo.com.au
thanks

find out no of words in a textbox so easily

take a text box and a command button
private command1_click()
c=0
for i=0 to len(text1.text)
if mid(text1,i,1)=" " then
c=c+1
end if
''this line for checking two spaces
if mid(text1,i,1)=" " then i=i+2
msgbox "no of word in textbox is" & c+1
end sub

Count no of words in a string easily

Private Sub command1_click()
c = 0
For i = 1 To Len(Text1.Text)
If Mid(Text1.Text, i, 1) = " " Then
c = c + 1
End If
''this line for checking two spaces
If Mid(Text1, i, 1) = " " Then i = i + 2
Next
MsgBox "no of word in textbox is" & c + 1
End Sub

sir happily saying tht this

sir happily saying tht this code works but works only in a small text box if u try to use this code in a text box with scrolls i mean when u try to count words of a paragraph or a document it fails, its useful for a short sentence but a good code, i wish if u could develop such a code equally good for a single line or a whole book, a file or files, who could show total count of numbers and total count of alphabets and their detail as well in a tabular form if u can develop plz do it, and send in here and also if u like to send me, this is my email address, koolpinkguy@yahoo.com.au.....................thanks

wew

it doesn't work good because if you don't type anything on the textbox the result would be "no of words is 1"...

Please ignore it

please ignore it