In this post, you’ll learn about logical operators in Excel VBA and how to use them for various operations with-in your Excel workbook.
Logical Operators in Excel VBA
Logical operators such as And, Or, Not are supported by Excel VBA. They are used to comparing values. They return values in a Boolean form that is either True or False. Let’s see them in detail with an example.
AND- Logical Operator
Logical operator AND is used to compare two or more conditions. If the conditions are met completely they return the value True or else False. Let’s see it with an example.
Sample program using AND operator in Excel VBA
Code:
Sub LogicalAND ()
Dim intA As Integer
Dim intB As Integer
Dim Result As Boolean
intA = 57
intB = 57
If intA = 57 And intB = 57 Then
Result = True
Else
Result = False
End If
MsgBox Result
End Sub
Or – Logical Operator
Similar to AND operator, the OR logical operator compares two values. When either of the condition is met it returns True, if not then False. Let’s see it with an example.
Sample program using OR operator in Excel VBA
Code:
Sub LogicalOR()
Dim intA As Integer
Dim intB As Integer
Dim Result As Boolean
intA = 57
intB = 111
If intA = 57 Or intB = 105 Then
Result = True
Else
Result = False
End If
MsgBox Result
End SubNOT – Logical Operator
The Not logical operator in Excel VBA checks for one or more conditions. If the conditions are met, the operator returns False. Otherwise, it returns True. Let’s see it with an example.
Sample program using NOT logical operator in Excel VBA.
Code:
Sub LogicalNOT()
Dim intA As Integer
Dim Result As Boolean
intA = 57
If Not (intA = 56) Then
Result = True
Else
Result = False
End If
MsgBox Result
End Sub
