Logical Operators

The three most used logical operators in VBA are: And, Or and Not. thees are used to compare conditions.

1. Logical AND operator - it returns true when all the condition are true, if any one condition is false then it will return false, we can use thees return value to execute other codes.


Example of "and" operator

Dim score1 As Integer
dim score2 As Integer
dim result As String

score1 = Range("A1").Value
score2 = Range("B1").Value

If score1 >= 60 And score2 > 33 Then
result = "pass"
Else
result = "fail"
End If

Range("C1").Value = result


in above example if the score1 is greater then or equal to 60 and score2 is greater then 33 then it will write Pass in cell "C1". else it will it will write Fail in cell "C1".


2.Logical OR operator - it returns true when any of the condition is true, if all conditions are false then it will return false, we can use thees return value to execute other codes.



Example of "OR" operator

Dim score1 As Integer
dim score2 As Integer
dim result As String

score1 = Range("A1").Value
score2 = Range("B1").Value

If score1 >= 60 or score2 > 33 Then
result = "pass"
Else
result = "fail"
End If

Range("C1").Value = result


in above example if the score1 is greater then or equal to 60 or score2 is greater then 33 then it will write Pass in cell "C1". else it will it will write Fail in cell "C1".

3.Logical NOT operator - it returns true when first condition is true, and not condition is also true then it will return false, we can use thees return value to execute other codes.



Example of "NOT" operator

Dim score1 As Integer
dim score2 As Integer
dim result As String

score1 = Range("A1").Value
score2 = Range("B1").Value

If score1 >= 60 NOT score2 > 33 Then
result = "pass"
Else
result = "fail"
End If

Range("C1").Value = result


in above example if the score1 is greater then or equal to 60 and score2 is not greater then 33 then it will write Pass in cell "C1". else it will it will write Fail in cell "C1".

Post a Comment

0 Comments