The most common logical operators in VBA are: AND and OR. Each of these operators is very useful for evaluating conditions and making appropriate decisions about the code that will be executed
The AND Logical Operator
The AND logical operator is the operator that helps us to enforce two conditions. This operator allows to execute a block of code that must meet condition1 AND condition2.
In the following example I have the qualification of two exams. Only if both exams have a grade higher than 3, then the student will be approved, otherwise the grade will be disapproval.
We are going to use an IF statement to compare the exams qualification with the grade condition. This comparison is that we usually do with the logical operators.
The code that will be executed when the button is pressed will be the following:
When we execute this code we will obtain the “Approved” result, this is because both exams have a rating greater than 3:
In this way we verify that the logical operator And helps us to force both conditions to be fulfilled. However, if the value of one of the cells is less than 3, then we will have a different result:
The logical operator And will return the true value only when both conditions are met and it will suffice that one of them is not met to obtain a negative result.
The OR Logical Operator
The OR logical operator translates will allow us to know if at least one of the conditions is fulfilled, that is to say, if the condition1 OR condition2 is fulfilled.
If we change the previous example a bit and say that it is sufficient that one of the two grades is greater than 3 for the student to be approved, then we can modify the code as follows:
If any of the grades are higher than 3, then the student will be approved:
The only way the logical OR operator returns a false value is that none of the conditions are met. In our example, the student will be reprobate only when both grades are less than 3:
To conclude in the following table we can see in each case how the logical operators evaluate the condition: