HOWTO: Capitalize the First Letter of Each Word in a String

ID: Q109220

The information in this article applies to:

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.
Keywords          : kbprg PrgOther vbwin 
Version           : WINDOWS:2.0 3.0
Issue type        : kbhowto

Last Reviewed: September 30, 1997