Friday, October 7, 2022

Summary Operator Is, Like, Mod and Not in Excel VBA

Even though Operator Is, Like, Mod and Not totally different in comparison but sometime difficult to remember which one need to use. Here comparison table for reference.

No. Operator Logical
1 Is Compare two object reference variables.
2 Like Compare two strings.
3 Mod Divide two numbers and return only the remainder.
4 Not Perform logical negation on an expression.

Operator Commonly Use for
Is ObjectA Is ObjectB = TRUE/FALSE
Is MyRange Is Nothing = TRUE/FALSE
Is Intersect(MyRange,Selection) Is Nothing = TRUE/FALSE
Like String Like String Pattern(*,#,?,[!]) = TRUE/FALSE
Mod A=7,B=2, A Mod B = 1 (Balance for 2*3=6)
Not A=7,B=2. Not (A > B) = FALSE, Not (A < B) = TRUE

VBA Vode:

Option Explicit
Sub OperatorIsLikeModNot()
    
    Dim MySheet As Worksheet
    Dim iNumA As Integer, iNumB As Integer
    Dim StrUrlA As String, StrUrlB As String
    
    Dim MyRange As Range, MySelect As Range
    
    Set MySheet = ActiveSheet
    Set MyRange = MySheet.Range("A1:D20")
    Set MySelect = Selection
    StrUrlA = "https://mrvba.blogspot.com/"
    StrUrlB = "C:\Users\UserName\Desktop\AlQuran MP3"
    iNumA = 10: iNumB = 3
    
    'Combination Is and Not Operator
    If Not MySheet Is Nothing Then
        Debug.Print MySheet.Name
        'Combination Is Intersect and Not Operator
        If Not Intersect(MySelect, MyRange) Is Nothing Then
            Debug.Print "Your Selected cell is in range A1 to D20."
        Else
            Debug.Print "Your Selected cell is Not in range."
        End If
        'Operator Like
        If StrUrlA Like "https://*" Then
            Debug.Print "Yes! This is URL:" & StrUrlA
        Else
            Debug.Print "This is not Url:" & StrUrlB
        End If
        If StrUrlB Like "https://*" Then
            Debug.Print "Yes! This is URL:" & StrUrlA
        Else
            Debug.Print "This is not Url:" & StrUrlB
        End If
        'Operator Mode and And operator
        If IsNumeric(iNumA) And IsNumeric(iNumB) Then
            Debug.Print iNumA Mod iNumB
        End If
        'Operator Not
        If Not (iNumA > iNumB) Then
            Debug.Print "No: " & iNumA & " is Less than " & iNumB
        ElseIf Not (iNumA < iNumB) Then
            Debug.Print "Yes: " & iNumA & " is more than " & iNumB
        End If
    End If

End Sub

Note:
Most commonly use Operator among these is Not and Is, sometime only use like and seldom use Mod.

Microsoft Reference-Is-operator
Microsoft Reference-Like-operator
Microsoft Reference-Mod-operator
Microsoft Reference-Mod-operator example
Microsoft Reference-Not-operator

Practice makes perfect. Thank You.

excel training beginners
coding in vba
excel training online
visual basic for applications

No comments:

Post a Comment