Wednesday, March 14, 2012

Count the number of words in a textbox

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.

Text1 = Trim(Text1) ' Remove All SpacesWhile InStr(1, Text1, " ") > 0 'Remove Double Spaces    StartPos = InStr(1, Text1, " ")    Text1 = Mid(Text1, 1, StartPos - 1) & _                Mid(Text1, StartPos + 1, Len(Text1) - StartPos)        If Mid(Text1, Counter, 1) = " " Then 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.


View the original article here

No comments:

Post a Comment