Visual Basic 2008 Programming: Business Applications with a Design Perspective
Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9
Chapter 10 Chapter 11 Chapter 12 Chapter 13 Chapter 14 Appendix A Appendix B Appendix C Home
Loading
Last change: February 13 2016 18:48:19.

 Chapter in PDF

Table of Contents

Chapter 5: Decision
Last change: February 13 2016 18:47:58.
<<PreviousNext>>

5.2   The If Block

Recall that a simple If statement has the following syntax:

If Condition Then Statement

When the expression in the condition portion is True, the statement portion is executed; otherwise, it is ignored. For example, you can code the following:

If Score > = 90 Then Grade = “A”

This statement says if Score is greater than or equal to 90, an “A” is assigned to Grade. If Score is less than 90, nothing is assigned to Grade because the statement portion is ignored.
Note that the condition can be any logical expression. In addition, recall that an expression can be as simple as a variable, control property, or constant, as explained in Chapter 4; therefore, it is correct to code the following:

If rbtMale.Checked Then Sex = “M”

This statement says if rbtMale.Checked is True, assign “M” to the variable, Sex. Because the Checked property of the radio button rbtMale is either True or False (which is what the computer is checking for), there is no need to code:

If rbtMale.Checked = True Then Sex = “M”

Any expression that can be evaluated to a Boolean value (either True or False) can be placed in the condition portion:

If CBool(A) Then cboZipCode.SelectedIndex = 0

Note that A is assumed to be a numeric variable in this line. The SelectedIndex property of the combo box, cboZipCode, will be set to 0 when A is any value but zero. Recall again that a numeric expression is converted to True when it is nonzero and False when zero.

Tip
In practice, you will find that the simple If statement is seldom used because in most cases either more than one statement will have to be executed or a more complex If structure is called for. Actually, this simple If statement can become a point of confusion. Use the simple If block discussed immediately below even if only one statement is to be executed. It offers the flexibility of adding more statements to execute. It is also easier to trace the logic of your program.
Last change: February 13 2016 18:47:57.
  1. Relational Operators
  2. Assignment Statements
  3. Logical Operators
  4. Operational Precedence
  • 5.2 The If Block
    1. Simple If Block
    2. The If…Then…Else…End If Block
    3. The If…Then…ElseIf…Then…Else…End If Block
    4. Nesting If Blocks
    5. Additional Notes on Coding the If Block
    6. <<PreviousNext>>