How to Count Words in a Textbox in Visual Basic (VB)

Written by jaime avelar
  • Share
  • Tweet
  • Share
  • Pin
  • Email
How to Count Words in a Textbox in Visual Basic (VB)
Use Visual Basic to search for words in a string. (John Foxx/Stockbyte/Getty Images)

String manipulation can be a hassle using String Methods, but to speed up the process, you can use the Regex Class to quickly manipulate strings. The Regex class is commonly used to parse large amounts of text to replace, edit, or delete data in a string. Use the Matches Method to quickly count the words in a string. This method searches the string for all occurrences of a regular expression, such as words.

Skill level:


  1. 1

    Launch Microsoft Visual Basic Express. Click "New Project" from the left pane of the window, and select "Windows Forms Application." Click "OK."

  2. 2

    Double-click "TextBox" from the "Toolbox" pane to add a new checkbox control to the Form. Double-click "Button" to add a new button. Double-click "Button1" to open the Visual Basic Window.

  3. 3

    Copy and paste the following in the first line to declare the Regex Class namespace:

    Imports System.Text.RegularExpressions

  4. 4

    Copy and paste the following code below "Button1_Click" to declare one variable and get the string typed in the text box by the user:

    Dim word String As String

    word String = Me.TextBox1.Text.ToString()

  5. 5

    Copy and paste the following code to get the word count from the string variable:

    Dim wrdCnt As MatchCollection = Regex.Matches(word String, "[\S]+")

  6. 6

    Copy and paste the following code to display the word count using a message box:


  7. 7

    Press "F5" to run your program and type a sentence into the text box. Press "Button1" to display the word count.

Don't Miss

  • All types
  • Articles
  • Slideshows
  • Videos
  • Most relevant
  • Most popular
  • Most recent

No articles available

No slideshows available

No videos available

By using the site, you consent to the use of cookies. For more information, please see our Cookie policy.