Wednesday, September 28, 2022

Comparison Operator in Excel VBA

 Basically 6 types of comparison operator as below table.

No. Operator Compare Value
1 < Less Than
2 <= Less than or equal to
3 > Greater than
4 >= Greater than or equal to
5 = Equal to
6 <> Not equal to

Comparison operator to be use either compare 2 value or checking certain condition example empty or null but mostly to check numeric value as below either True or False. Inside Green and Yellow cell we have formula =Num1 Operator Num2 example inside Range("E3") =B3<D3 then answer is TRUE.

 

VBA Code:

Option Explicit
Sub ComparisonOperator()
    Dim i As Integer
    Dim Cell As Range, MyRng As Range
     
    With ActiveSheet
        i = 3
        Do
            'For < Less Than
            .Range("E" & i) = .Range("B" & i) < .Range("D" & i)
            'For <= Less than or equal to
            .Range("F" & i) = .Range("B" & i) <= .Range("D" & i)
            'For > Greater than
            .Range("G" & i) = .Range("B" & i) > .Range("D" & i)
            'For >= Greater than or equal to
            .Range("H" & i) = .Range("B" & i) >= .Range("D" & i)
            'For = Equal to
            .Range("I" & i) = .Range("B" & i) = .Range("D" & i)
            'For <> Not equal to
            .Range("J" & i) = .Range("B" & i) <> .Range("D" & i)
            i = i + 1
        Loop While .Range("A" & i) <> ""
        Set MyRng = .Range("E3:J5")
        For Each Cell In MyRng
            If Cell.Text = "TRUE" Then
                Cell.Interior.ColorIndex = 4
            Else
                Cell.Interior.ColorIndex = 6
            End If
        Next
    End With
    
End Sub

Microsoft Reference-Comparison-operators

Practice makes perfect. Thank You.

No comments:

Post a Comment