Logo

Conditional Statements

 

Overview of Conditions

 

Introduction

The essence of computer programming relies on telling the computer what to do when something occurs, and how to do it. This is performed by setting conditions, examining them and stating what decisions the computer should make.

Microsoft Visual Basic uses various conditional statements for almost any situation your computer can encounter. As the application developer, it is up to you to anticipate these situations and make your program act accordingly.

 

Practical Learning: Using an If...Then Statement

  1. Start Microsoft Visual Basic and accept to use Standard EXE by pressing Enter
  2. Right-click the form and click View Code
 

The If...Then Statement

The If...Then statement examines the truthfulness of an expression. Structurally, its formula is:

If ConditionToCheck Then Statement

Therefore, the program examines a condition, in this case ConditionToCheck. This ConditionToCheck can be a simple expression or a combination of expressions. If the ConditionToCheck is true, then the program will execute the Statement.

There are two ways you can use the If...Then statement. If the conditional formula is short enough, you can write it on one line, like this:

If ConditionToCheck Then Statement

If there are many statements to execute as a truthful result of the condition, you should write the statements on alternate lines. Of course, you can use this technique even if the condition you are examining is short. In this case, one very important rule to keep is to terminate the conditional statement with End If. Here is an example:

If ConditionToCheck Then
    Statement
End If

Here is another example:

If Condition Then
    Statement1
    Statement2
    Statementn
End If
 

Practical Learning: Using an If...Then Statement

  1. In the Code Editor, click the arrow of the Object combo box and select Form
  2. Click the arrow of the Procedure combo box and select Click
  3. Implement the events as follows:
     
    Private Sub Form_Click()
        If BackColor = vbRed Then BackColor = vbBlue
    End Sub
    
    Private Sub Form_Load()
        BackColor = vbRed
    End Sub
  4. Press F5 to test the application
  5. Click somewhere in the form to change its color
  6. After using the form, close it and return to MSVB

The If...Then...Else Statement

The If...Then statement offers only one alternative: to act if the condition is true. Whenever you would like to apply an alternate expression in case the condition is false, you can use the If...Then...Else statement. The formula of this statement is:

If ConditionToCheck Then
    Statement1
Else
    Statement2
End If

When this section of code is executed, if the ConditionToCheck is true, then the first statement, Statement1, is executed. If the ConditionToCheck is false, the second statement, in this case Statement2, is executed.

 

Practical Learning: Using an If...Then...Else Statement

  1. To use the new condition, change the form's Click event as follows:
     
    Private Sub Form_Click()
        If BackColor = vbRed Then
            BackColor = vbBlue
        Else
            BackColor = vbRed
        End If
    End Sub
  2. Press F5 to test the application
  3. Click the form a few times to change its color
  4. Close the form and return to MSVB

The If...Then...ElseIf Statement

The If...Then...ElseIf statement acts like the If...Then...Else expression, except that it offers as many choices as necessary. The formula is:

If Condition1 Then
    Statement1
ElseIf Condition2 Then
    Statement2
ElseIf Conditionk Then
    Statementk
End If

The program will first examine Condition1. If Condition1 is true, the program will execute Statment1 and stop examining conditions. If Condition1 is false, the program will examine Condition2 and act accordingly. Whenever a condition is false, the program will continue examining the conditions until it finds one. Once a true condition has been found and its statement executed, the program will terminate the conditional examination at End If.

There is still a possibility that none of the stated conditions is true. In this case, you should provide a "catch all" condition. This is done with a last Else section. The Else section must be the last in the list of conditions and would act if none of the primary conditions is true. The formula to use would be:

If Condition1 Then
    Statement1
ElseIf Condition2 Then
    Statement2
ElseIf Conditionk Then
    Statementk
Else
    CatchAllStatement
End If

 

 

Practical Learning: Using an If...Then Statement

  1. To use the new expression, change the form's Click event as follows:
     
    Private Sub Form_Click()
        If BackColor = vbRed Then
            BackColor = vbBlue
        ElseIf BackColor = vbBlue Then
            BackColor = vbGreen
        ElseIf BackColor = vbGreen Then
            BackColor = vbBlack
        Else
            BackColor = vbRed
        End If
    End Sub
  2. Test the application
  3. Close it and return to MSVB
 

The Select Case Statement

If you have a large number of conditions to examine, the If...Then...Else will go through each one of them. Visual Basic offers the alternative of jumping to the statement that applies to the state of the condition.

The formula of the Select Case is:

Select Case Expression
    Case Expression1
        Statement1
    Case Expression2
        Statement2
    Case Expressionk
        Statementk
End Select

The Expression will examined and evaluated once. Then it will compare the result of this examination with the Expression of each case. Once it finds one that matches, it would execute the corresponding Statement.

If you anticipate that there could be no match between the Expression and one of the Expressions, you can use a Case Else statement at the end of the list. The statement would then look like this:

Select Case Expression
    Case Expression1
        Statement1
    Case Expression2
        Statement2
    Case Expressionk
        Statementk
    Case Else
        Statementk
End Select
 

Practical Learning: Using a Select Case Statement

  1. To use a Select Case expression, change the form's Click event as follows:
     
    Private Sub Form_Click()
        Select Case BackColor
            Case vbRed
                BackColor = vbBlue
            Case vbBlue
                BackColor = vbGreen
            Case vbGreen
                BackColor = vbBlack
            Case Else
                BackColor = vbRed
        End Select
    End Sub
  2. Test the application then close it
 

Loops Repeaters

 

Introduction

A loop is an expression used to repeat an action. Visual Basic presents many variations of the loops and they combine the Do and the Loop keywords.

 

The Do...While Loop

The formula of the Do... While loop is:

Do While Condition
    Statement(s)
Loop

This expression examines the Condition. If the condition is true, then it executes the Statement or statements. After executing the statement(s), it goes back to examine the Condition. AS LONG AS the Condition is true, the Statement will be executed and the Condition will be tested again. If the Condition is false or once the condition becomes false, the statement will not be executed and the the program will move on. As you may guess already, the Condition must provide a way for it to be true and to be false.

 

The Do...Loop...While Statement

Since the Do...While statement tests the Condition first before executing the Statement, sometimes you will want the program to execute the Statement first, then go back and test the Condition. Visual Basic offers a reverse to the formula, which is:

Do
  Statement(s)
Loop While Condition

In this case, the Statement or Statements will be executed first. Then the Condition will be tested. If the Condition is true, the program will execute the Statement again. The program will continue this examination-execution as long as the Condition is true. The big difference here is that even if the Condition is false, the program will have executed the Condition at least once.

 

The Do...Until...Loop Statement

An alternative to the Do...While loop is the Do...Until loop. Its formula is:

Do Until Condition
    Statement(s)
Loop

This loop will first examine the Condition, instead of examining whether the Condition is true, it will test whether the Condition is false.

 

The Do...Loop...Until Statement

An alternative to the Do...Until...loop consists of executing the the Statement first. The formula is:

Do
    Statement(s)
Loop Until Condition

This express executes the Statement first. After executing the Statement, it would examine the Condition. If the Condition is False, then it would go back and execute the Statement again and re-check the Condition. Once the Condition becomes true, it would stop and move on; but as long as the Condition is False, the Statement would be executed.

 

Loop Counters

 

Introduction

The looping statements we reviewed above are used when you don't know or can't anticipate the number of times a condition needs to be checked in order to execute a statement. If you know with certainty how many times you want to execute a statement, you can use another form of loops that use the For...Next expression.

The For...To...Next Loop

 One of the loop counters you can use is For...To...Next. Its formula is:

For Counter = Start To End
  Statement(s)
Next

Used for counting, the expression begins counting at the Start point. Then it examines whether the current value (after starting to count) is greater than End. If that's the case, it then executes the Statement(s). Next, it increments the value of Counter by 1 and examines the condition again. This process goes on until the value of Counter becomes equal to the End value. Once this condition is reache, the looping stops.

 

Stepping the Counting Loop

The formula above will increment the counting by 1 at the end of each statement. If you want to control how the incrementing processes, you can set your own, using the Step option. Here is the formula:

For Counter = Start To End Step Increment
  Statement(s)
Next Counter

You can set the incrementing value to your choice. If the value of Increment is positive, the Counter will be added its value. This means that you can give it a negative value, in which case the Counter will be subtracted the set value.

 

For Each Item In the Loop

Since the For...Next loop is used to execute a group of statements based on the current result of the loop counting from Start to End, an alternative is to state various steps in the loop and execute a group of statements for each one of the elements in the group. This is mostly used when dealing with a collection of items.

The formula is:

For Each Element In Group
    Statement(s)
Next Element

The loop will execute the Statement(s) for each Element in the Group.

 

Logical Operators

 

Introduction

A logical operation is one that is performed on one or two expressions to check the truthfulness or falsity. Logical operators are performed only on conditional statements.

 

Logical Conjunction: AND

A logical conjunction is an operation used to check two conditions for absolute truthfulness. This operation uses the AND keyword. The formula to use the AND operator is

Condition1 AND Condition2

The left condition, Condition1, is first checked. If it is False, the whole expression is rendered False and the checking process stopped. If the left condition is True, then the right condition, Condition2, is checked. If the right condition is False, the whole expression is False, even if the first is True. In the same way, if both conditions are false, the whole expression is False. Only if both conditions are True is the whole condition true. This can be resumed as follows:

 
Condition1 Condition2 Condition1 AND Condition2
False Don't Care False
Don't Care False False
True True True
 

Logical Disjunction: OR

 

A logical disjunction is performed on two conditions for a single truthfulness. This operation uses the OR keyword on the following formula:

Condition1 OR Condition2

 The left condition, Condition1, is first checked. If Condition1 is True, then the whole expression is true, regardless of the outcome of the second. If Condition1 is False, then Condition2 is checked. If Condition2 is True, the whole expression is True even if Condition1 is False. In the same way, if both conditions are True, the whole expression is True. The whole expression is false only if both Condition1 and Condition2 are False. This can be resumed as follows:

Condition1 Condition2 Condition1 OR Condition2
True Don't Care True
Don't Care True True
True True True
False False False
 

Details on Conditional Statements

 

Mixed And Nested Conditional Statements

Sometimes you will find out that one conditional statement does not satisfy the criteria you are trying to apply to your program; you might have to have many conditions. Programming allows you to use as many conditions as necessary and to create some conditions inside of others.

Mixing conditions is the ability to use different conditional statements in your program. Nesting is the ability to put some conditions inside of others. These two techniques make your programs more efficient.

Built-in Logical Constants: NULL

A variable is said to be null when its value is invalid or doesn't bear any significant or recognizable value.

 

Built-in Logical Constants: TRUE and FALSE

An expression is said to be false if the result of its comparison is 0. Otherwise, the expression is said to bear a true result.

 

Previous Copyright © 2002-2005 FunctionX, Inc. Next