Tip:
Highlight text to annotate it
X
In this lesson, we will discuss If-Then structures.
The simplest type of If structure is an If-Then structure.
An If-Then structure enables you to execute a set of statements only if a test condition is True.
If-Then structures begin with: If, a test condition, and Then.
If the test condition is True, then the statements inside the If structure will be executed.
If the test condition is False, then the statements inside the If structure will not be executed.
The If-Then structure is terminated with the End If statement.
It is considered good programming practice to indent the statements inside the If-Then structure by a few spaces because it will make
your code easier to read, but indentation is optional.
The parentheses around the test condition also are optional.
Here is an example of how to use an If-Then structure.
After running this program, two message boxes will appear.
The first message box states: Inside If structure
The second message box states: y = 300
At the beginning of the program two Double variables named x and y are created, and assigned the values 40 and 50.
Next we come to an If structure.
If the test condition x > 10 is True, then we will execute all statements between If and End If.
If the test condition x > 10 is False, we will bypass the entire If structure.
In this case, 40 > 10, so we enter the If structure.
A message box displays the text “Inside If structure” and y is assigned the value 300.
We reach the end of the If structure and continue on in our code.
A message box appears that displays “y =” and the current value of y, which is 300.
Let's see what happens when we change the test condition from x greater than 10 to x less than 10.
When we run our code, only one message box appears which states “y = 50”.
As before, two Double variables named x and y are created, and assigned the values 40 and 50.
The test condition x less than 10 is False since 40 is greater than 10.
So we bypass all the statements between If and End If.
The first and only message box that is displayed states “y =” the current value of y, which is still 50.
Notice how parentheses are placed around the test condition and the statements inside the If structure are indented a few spaces.
Although both of these actions are optional, they can help make your code easier to read.