Conditional
Statements
The syntax of the conditional statement:
If
(boolean expression) Then
The code to execute if the
boolean expression is equal to True
Else
The code to
execute if the boolean expression is equal to False
End If
Lets
make a password protected program.
We want to prompt the user to enter
the password
at the very start of the program, so put the following
code
in the Form_Load event:
Dim Password As String
Password =
InputBox("Please enter the password")
If (Password = "let me in")
Then
MsgBox "The Password is correct!"
Else
MsgBox "Incorrect Password!"
End If
Run the program.
An
InputBox is appearing.
Type "let me in" (without the quotes) in the
InputBox.
Note that the text is case sensitive, and if you will
type "LET
ME IN" you will get a message box with the
text "Incorrect
Password!".
Lets understand how this code works:
The boolean expression (Password =
"let me in") value is True
ONLY if the Password
variable value is "let me in".
If this boolean expression's value is
True, the code
that will be executed is the code that located
between
the Then and the
Else (MsgBox "The Password is correct!")
If this boolean
expression's value is False, and this
happens when the Password variable
value is NOT "let me in",
the code that will be executed is the code that
located between
the Else
and the End If (MsgBox "Incorrect
Password!")
If you
enter a wrong password, a message box is appearing,
but the program is
continue running.
To end the program, use the command End .
This
command is simply shut down the program.
Put the End
command in the "Else Section":
Dim Password As String
Password =
InputBox("Please enter the password")
If (Password = "let me in")
Then
MsgBox "The Password is correct!"
Else
MsgBox "Incorrect Password!"
End
End If