Visual Basic 6.0 Guide
Selection - The If Statement

Selection

Selection means writing code that will only be run when a condition is true or false. There are many ways to do this in Visual Basic.

  • If Then
  • If Then ... Else
  • If Then ... ElseIf
  • Select Case

If Then

Try the following example code in a new project containing a text box called txtAge and a command button called cmdCanDrive

Private Sub cmdCanDrive_Click()
Dim intAge As Integer
intAge = txtAge.Text
If intAge > 16 Then
MsgBox "You are old enough to drive."
End If
End Sub

Study the lines of code carefully. The first line declares a variable to stored the age. The second line sets this variable to be equal to the number entered in the text box. You will only see the message box if you enter a number above 16. This means that the line of code that does this only runs when intAge > 16. Notice that we have to write End If at the end of this programming construct.

If Then ... Else

Try out the following. Note that you will now get a message box if you are too young as well as if you are old enough.

Private Sub cmdCanDrive_Click()
Dim intAge As Integer
intAge = txtAge.Text
If intAge > 16 Then
MsgBox "You are old enough to drive."
Else
MsgBox "You are too young to drive."
MsgBox "Sorry, Barry."
End If
End Sub

If Then ... ElseIf

Let's move things on a little bit. Try out the following.

Private Sub cmdCanDrive_Click()
Dim intAge As Integer
intAge = txtAge.Text
If intAge > 16 Then
MsgBox "You are old enough to drive."
ElseIf intAge = 16 Then
MsgBox "You can drive next year."
Else
Msgbox "You are way too young for driving."
End If
End Sub