Microsoft Office Tutorials and References
In Depth Information
Making Decisions in VBA Code
Nesting If...End If statements
What if you have more than two possible scenarios? No problem — you
can nest If...End If blocks, meaning that you can put one complete
If...End If block inside another If...End If block. In the code
shown in Figure 3-3, for example, the innermost statements execute only if
Condition1 and Condition2 result in True.
Figure 3-3:
Nested
If...
End If
blocks.
You can see why the nested If...End If statements work if you look at
what happens when either test proves to be False:
If condition1 proves to be False, all code down to the last End If
statement is skipped. The inner If...End If block isn’t seen or
executed.
If condition1 proves to be True but condition2 proves to be False,
all the statements in the nested block are ignored. The innermost
statements still don’t execute.
If both condition1 and condition2 prove to be True, no code is
skipped, and the innermost statements execute normally.
You can nest If...Else...End If blocks as deeply as you want, but you
have to make sure that each block has its own End If statement.
Using a Select Case block
What if you have more than two or three cases to check for? Suppose that
you need to perform different statements depending on which of ten product
types a customer ordered. You could nest a lot of If...End If blocks, but
that code would be confusing. Luckily, Access provides a better way.
A Select Case block of code performs a particular set of instructions,
depending on some value. Typically, the value is a number that represents
some previous selection, and it’s stored in a variable or field in a table. The
basic syntax of a Select Case block of code looks like this:
Search JabSto ::




Custom Search