Using lfEnd If statements

You have a couple of ways to write VBA code that's capable of making a decision. The simplest — and by far the most common — is the lf...End If block of code, which uses this syntax:

If condition Then [statements]... [Else]

[statements]... End If where condition is an expression that results in True or False, and statements refers to any number of valid VBA statements. If the condition proves True, the statements between Then and Else execute, and all other statements are ignored. If the condition proves False, only the statements after the Else statement execute, as illustrated in Figure 4-8.

If condition Then

Figure 4-8:

The basic idea behind the If...

End If statement.

statementl statement2 statements

If condition proves True, only these statements are executed.

Else statement4 statement5

If condition proves False, only these statements are executed.

End If

You have a little bit of flexibility when using If...End If. If only one line of code executes for a True result and only one line executes for a False result, you can put the whole statement on a single line and omit the End If statement, as this line shows:

If State="NY" Then TaxRate=0.075 Else TaxRate=0

In some situations, you might need to have your code make a decision based on several possibilities. For example, perhaps you need to perform different statements depending on which of ten product types a person ordered. In that case, you can set up a Select Case block of code, which performs a particular set of instructions depending on some value. Typically, the value is stored in a variable or field in a table and is also a number that represents some previously made selection.

The basic syntax of a Select Case block of code looks like this:

Select Case value

[Case possibleValue [To possibleValue]

[statements]] [Case possibleValue [To possibleValue]

[statements]] End Select where value is some value (like a number), and possibleValue is any value that could match the value. You can have any number of Case possibleValue statements between the Select Case and End Select statements. Optionally, you can include a Case Else statement, which specifies statements that execute only if none of the preceding Case possibleValue statements proves True.

0 0

Post a comment

  • Receive news updates via email from this site