IfThen Else Statement

Now you know how to display a message or take an action when one or more conditions are true or false. What should you do, however, if your procedure needs to take one action when the condition is true and another action when the condition is false? By adding the Else clause to the simple If.. .Then statement, you can direct your procedure to the appropriate statement depending on the result of the test.

The If.. .Then.. .Else statement has two formats: single line and multi-line. The single-line format is as follows:

If condition Then statementl Else statement2

The statement following the Then keyword is executed if the condition is true, and the statement following the Else clause is executed if the condition is false. For example:

If sales > 5000 Then Bonus = sales * 0.05 Else MsgBox "No Bonus"

Part I

If the value stored in the variable sales is greater than 5,000, Visual Basic will calculate the bonus using the following formula: sales * 0.05. However, if the variable sales is not greater than 5,000, Visual Basic will display the message "No Bonus."

The If.. .Then.. .Else statement should be used to decide which of two actions to perform. When you need to execute more statements when the condition is true or false, it's better to use the multi-line format of the If.. .Then.. .Else statement:

If condition Then statements to be executed if condition is True

Else statements to be executed if condition is False End If

Notice that the multi-line (block) If.. .Then.. .Else statement ends with the End If keywords. Use the indentation as shown above to make this block structure easier to read.

If Me.Dirty Then

MelbtnUndo.Enabled = True

Else

MelbtnUndo.Enabled = False End If

In the above example, if the condition (Me.Dirty) is true, Visual Basic will execute the statements between Then and Else, and will ignore the statement between Else and End If. If the condition is false, Visual Basic will omit the statements between Then and Else, and execute the statement between Else and End If. The purpose of this procedure fragment is to enable the Undo button when the data on the form has changed and keep the Undo button disabled if the data has not changed. Let's look at the procedure example.

0 0

Post a comment