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

Article translations Article translations
Article ID: 109220 - View products that this article applies to.
This article was previously published under Q109220
Expand all | Collapse all

On This Page

SUMMARY

This article demonstrates how to capitalize the first letter of each word in a string.

MORE INFORMATION

Step-by-Step Example

The following example capitalizes the first word, and any word preceded by 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.

Properties

Article ID: 109220 - Last Review: June 29, 2004 - Revision: 2.1
APPLIES TO
  • 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
Keywords: 
kbhowto kbprogramming KB109220
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.

Give Feedback

 

Contact us for more help

Contact us for more help
Connect with Answer Desk for expert help.
Get more support from smallbusiness.support.microsoft.com