Nesting a Conditional Statement
Practical Learning: Nesting a Conditional Statement
Nesting an Immediate If Function
To get the functionality of an If...Then...ElseIf... conditional statement, you can nest one IIf() function in another. In reality, you would call the IIf() function in place of the FalsePart of another IIf() function. The nesting can be resolved as follows:
Function IIf(ByVal Expression As Boolean, ByVal TruePart As Object, Function IIf(ByVal Expression As Boolean, ByVal TruePart As Object, Function IIf(ByVal Expression As Boolean, ByVal TruePart As Object, Function IIf(ByVal Expression As Boolean, ByVal TruePart As Object, ByVal FalsePart As Object ) As Object ) As Object ) As Object ) As Object
By nesting IIf() calls, a long expression like the following can be written in one line:
Private Sub FirstName_LostFocus() If FirstName = "" Then If LastName = "" Then FullName = "" Else FullName = LastName End If Else FullName = LastName & ", " & FirstName End If End Sub
Practical Learning: Nesting an Immediate If Function
When you nest one condition in another condition as in:
If condition1 = True ' The first or external condition If condition2 = True ' The second or internal condition statement(s) End If End If
you are in fact saying "If condition1 verifies, Then if condition2 verifies, do this...". To support a simplified version of this scenario, the Visual Basic language provides the Boolean conjunction operator named And. Its primary formula is:
condition1 And Condition2 statement(s)
You must formulate each condition to produce a true or a false result. The result is as follows:
To make your code easier to read, it is a good idea to include each Boolean operation in its own parentheses.
Creating Many Conjunctions
Depending on your program, if two conditions are not enough, you can create as many conjunctions as you want. The formula to follow is:
condition1 And condition2 And condition3 And . . . And condition_n
When the expression is checked, if any of the operations is false, the whole operation is false. The only time the whole operation is true is if all of the operations are true.
Of course, you can nest a Boolean condition inside another conditional statement.
A Boolean disjunction is a combination of conditions where only one of the conditions needs to be true for the whole operation to be true. This operation is performed using the Boolean disjunction operator represented as Or. The primary formula to follow is:
condition1 Or condition2
The operation works as follows:
Combining Conjunctions and Disjunctions
Conjunctions and disjunctions can be used in the same expression. A conjunction (or disjunction) can be used to evaluate one sub-expression while a disjunction (or conjunction) can be used to evaluate another sub-expression.
As seen previously, one way you can combine conditional statements is by nesting them.