' Mr. Minich
' Period 1
' Ch5Demo3
' 12/7/2000
' Purpose - Illustrates the use of the Left, Right & Mid functions.
' Also, uses a sequential search (aka linear search) to find a blank space.
Option Explicit
Private Sub Form_Load()
' sets the appropriate display messages
lblPrompt.Caption = "Enter your first and last name separated by 1 space: "
lblFirstName.Caption = ""
lblLastName.Caption = ""
txtFullName.Text = ""
cmdClear.Caption = "&Clear"
cmdExit.Caption = "E&xit"
End Sub
Private Sub txtFullName_KeyPress(KeyAscii As Integer)
' displays first and last names separately
Dim intSpace As Integer ' position of space within full name
Dim intLength As Integer ' length of full name
Dim intCurrentPosition As Integer ' current position in search
If (KeyAscii = 13) Then
intLength = Len(txtFullName.Text) ' computing length of full name
For intCurrentPosition = 1 To intLength ' finding the space
If (Mid(txtFullName.Text, intCurrentPosition, 1) = " ") Then
intSpace = intCurrentPosition
Exit For
End If
Next intCurrentPosition
' This Do While loop could be used instead of a For Next loop.
' Do While (intSpace = 0)
' intCurrentPosition = intCurrentPosition + 1
' If (Mid(txtFullName.Text, intCurrentPosition, 1) = " ") Then
' intSpace = intCurrentPosition
' End If
' Loop
' displaying results
lblFirstName.Caption = "Your first name is " & Left(txtFullName.Text, (intSpace - 1))
lblLastName.Caption = "Your last name is " & Right(txtFullName.Text, (intLength - intSpace))
End If
End Sub
Private Sub cmdClear_Click()
' clears text box and output labels and sets focus appropriately
txtFullName.Text = ""
lblFirstName.Caption = ""
lblLastName.Caption = ""
txtFullName.SetFocus
End Sub
Private Sub cmdExit_Click()
' unloads the form and ends the program
Unload Me
End
End Sub
' The text box's KeyPress event is used instead of a "Click" command button to make the
' program easier and more natural to use.
' Technically the Do While loop is preferable to the For/Next loop since it does not require
' an Exit statement. Remember, that it is usually recommended that you avoid using Exit statements
' unless it makes your code a lot easier to read and understand.