XCELLGUY
XCELLGUY

Reputation: 179

Two strings check true for equal but check false for Like operator

Why doesn't the "Like" statement work?

The "=" statement checks as true but the "like" operator checks as false, why?

Sub sandbox2()

Dim TagForm As String

TagForm = "tag(1###)<EX-->"

Debug.Print "Compare: " & Sheets(2).Cells(2, 2).Value & " To: " & TagForm

If Sheets(2).Cells(2, 2).Value = TagForm Then 'this works... displays message "Match!"
    MsgBox "Match!"
End If

If Sheets(2).Cells(2, 2).Value Like TagForm Then 'this does not work... Does not display "Match!"
    MsgBox "Match!"
End If

End Sub

Upvotes: 0

Views: 53

Answers (2)

Pᴇʜ
Pᴇʜ

Reputation: 57683

You used the Like operator wrong. The # represents a single number digigt.

so you can compare the following:

Sub test()
    Dim a As String, b As String, c As String
    a = "tag(1###)<EX-->"
    b = "tag(1###)<EX-->"
    c = "tag(1000)<EX-->"

    Debug.Print b = a       'true
    Debug.Print b Like a    'false

    Debug.Print c = a       'false
    Debug.Print c Like a    'trua
End Sub

If you compare MyVar LIKE "tag(1###)<EX-->" then
MyVar can be anything from "tag(1000)<EX-->" to "tag(1999)<EX-->"

Upvotes: 1

Josh Eller
Josh Eller

Reputation: 2065

When using the like operator, # and - are both special characters.

To match the literal character #, add brackets around it, like [#]

See the full documentation here: https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/like-operator

Upvotes: 1

Related Questions