VBA Logical Operator

VBA Logical Operator. Let’s say you Want to Take a Customer Order, and for that, you First Want to Check Whether the Ordered item is Actually Available. If so, you Want to Double-Check the Amount of Each. Logical Operators Come in Handy in Such Instances.

The Main Excel VBA Logical Operators are AND, OR, and NOT.

Operator

Meaning

Syntax

AND

See if all conditions are true.

condition1 And condition2

OR

See if one or more conditions are true.

condition1 OR condition2

NOT

Negative. True/False are inverted.

NOT condition1

The and Logical Operator

The AND Operator also Accepts Multiple Arguments and Returns True or False. The And Operator Requires That all of the Individual Elements be True Before the Expression is Correctly Completed. The AND Operator Will Return False if Three Expressions are Joined Together, and two of Them Return True, but one Returns False.

Example

The first Expression Returns True, and the Second Returns False. When you Combine the two, the Whole Statement Returns False. We can Have Twenty true Expressions, but if one of Them is False, Then the Entire Expression Would be False.

Sub LogicalAndOperator()

MsgBox (1 + 2 = 3)

'Output : True

MsgBox (1 + 2 = 4)

'Output : false

MsgBox (1 + 2 = 3) And (1 + 2 = 4)

'Output : false

End Sub

The OR Logical Operator

The OR Operator Allows you to Test Multiple Conditions, but What you’re Really Trying to Determine is Whether the Combined Statement is True or False. If you Have Multiple Conditions, and one of Them Returns true, Then the Expression in its Entirety will Return True.

Example

The First Expression in the Code Below is True, While the Second Expression is False, and if I Combine the Two, the Whole Expression is True Because at Least one of the Expressions was True by Itself.  If the First Expression had Resulted in False, the Entire Expression Would have also Resulted in False.

Sub LogicalOROperator()

MsgBox (1 + 3 = 4)

'Output : True

MsgBox (1 + 3 = 5)

'Output : false

MsgBox (1 + 4 = 6) Or (1 + 3 = 3)

'Output : false

End Sub

The NOT Logical Operator

Using the Not Operator, you can Return the Opposite of What Your Expression Would Have Returned Without the Not Operator, Either as a Stand-Alone Basis or in Conjunction With the Or and And Operators Discussed Earlier.

In the Example Below, I Give the Regular Expression on the First line and Give the Expression Using the Not Operator on the Following Line.

Example

Sub LogicalNotOperator()

MsgBox True               'Output: true

MsgBox (1 + 3 = 4)        'Output: True

MsgBox Not True           'Output: False

MsgBox Not (1 + 3 = 4)    'Output: False

MsgBox False              'Output: False

MsgBox (1 + 3 = 5)        'Output: False

MsgBox Not False          'Output: True

MsgBox Not (1 + 3 = 5)    'Output: True

End Sub

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top