Making Decisions in VBA Code

Decision-making is a big part of programming because most programs need to be smart enough to figure out what to do, depending on the circumstances. Often, you want your code to do one thing if such-and-such is true but do something else if such-and-such is false. You use conditional expressions to determine whether something is true or false. A conditional expression is one that generally follows this syntax:

Value ComparisonOperator

Value

where Value is some chunk of information, and the ComparisonOperator

is one of those listed in Table 4-3.

Table 4-3

Comparison Operators

Operator

Meaning

= Equal to

<

Less than

<=

Less than or equal to

>

Greater than

>=

Greater than or equal to

<>

Not equal to

For example, the expression

[Last Name] = "Smith"

compares the contents of the [Last Name] field with the string "Smith". If the [Last Name] field does indeed contain the name Smith, the expression is (returns) True. If the [Last Name] field contains anything other than Smith, the expression returns False.

Another example is the following statement:

The contents of the Qty field are compared with the number 10. If the number stored in the Qty field is 10 or greater, the expression returns True. If the number stored in the Qty field is less than 10, the expression returns False.

You can combine multiple conditional expressions into one by using the logical operators summarized in Table 4-4.

Table 4-4

Logical Operators

Operator

Meaning

AND

Both are true

OR

One or both are true

NOT

Is not true

XOR

Exclusive or: One — not both — is true

The following conditional expression requires that the [Last Name] field contain Smith and the [First Name] field contain Janet in order for the entire expression to be True:

[Last Name]="Smith" and

[First Name]="Janet"

You can include spaces on either side of the equal sign or not. Either way works.

The following example is an expression that returns True if the State field contains either NJ or NY:

0 0

Post a comment