VBA Logical Operators in Microsoft Excel

Using VBA logical operators AND - OR

 

 

 

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.

 

VBA Logical Operators Initial Example

 

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:

 

VBA Logical Operators AND Code

 

When we execute this code we will obtain the “Approved” result, this is because both exams have a rating greater than 3:

 

VBA Logical Operator AND approved example

 

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:

 

AND Logical Operator Reprobate Example

 

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:

 

Code for OR logical operator example

 

If any of the grades are higher than 3, then the student will be approved:

 

OR logical Operator Approved Example

 

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:

 

OR Logical Operator Reprobate Example

 

To conclude in the following table we can see in each case how the logical operators evaluate the condition:

 

Conditions Table for VBA Logical Operators AND - OR

 

Excel Total 

 

 

4 Comments on VBA Logical Operators in Microsoft Excel

6 Trackbacks & Pingbacks

  1. educational websites for students
  2. education sites
  3. investment
  4. money investment advice
  5. financial advisors
  6. health problems

Comments are closed.