You are currently offline, waiting for your internet to reconnect

How To Capitalize the First Letter of Each Word in a String

This article was previously published under Q109220
Retired KB Content Disclaimer
This article was written about products for which Microsoft no longer offers support. Therefore, this article is offered "as is" and will no longer be updated.
This article demonstrates how to capitalize the first letter ofeach word in a string.

Step-by-Step Example

The following example capitalizes the first word, and any word precededby a space or carriage-return-plus-linefeed sequence.

  1. Start a new project in Visual Basic. Form1 is created by default.
  2. Add a Text Box and a CommandButton to Form1.
  3. Double-click the text box to open the code window. Add the following code to the LostFocus event for the Text box:
          Sub Text1_LostFocus ()         Dim t As String         t = Text1.Text  ' Put contents of text box                         ' into a string variable.         If t <> "" Then            Mid$(t, 1, 1) = UCase$(Mid$(t, 1, 1))            For i = 1 To Len(t) - 1               If Mid$(t, i, 2) = Chr$(13) + Chr$(10) Then                  ' Capitalize words preceded by carriage return plus                  ' linefeed combination. This only applies when the                  ' text box's MultiLine property is set to True:                  Mid$(t, i + 2, 1) = UCase$(Mid$(t, i + 2, 1))               End If               If Mid$(t, i, 1) = " " Then                  ' Capitalize words preceded by a space:                  Mid$(t, i + 1, 1) = UCase$(Mid$(t, i + 1, 1))               End If            Next            Text1.Text = t         End If      End Sub						
  4. Start the program or press the F5 key.
  5. Enter lowercase words in the text box. Click the CommandButton or press the TAB key to cause the text box to lose the focus. The first letter of each word in the text box will be capitalized. You may continue to enter more text and change the focus as often as you want. Close the form to end the program.

Article ID: 109220 - Last Review: 06/29/2004 21:15:49 - Revision: 2.1

  • Microsoft Visual Basic 2.0 Standard Edition
  • Microsoft Visual Basic 3.0 Professional Edition
  • Microsoft Visual Basic 2.0 Professional Edition
  • Microsoft Visual Basic 3.0 Professional Edition
  • kbhowto kbprogramming KB109220