两个字符串检查true表示相等,但检查false表示Like运算符



为什么"Like"语句不起作用?

"="语句检查为true,而"like"运算符检查为false,为什么?

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

您错误地使用了Like运算符。#表示单个数字数字。

因此您可以比较以下内容:

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

如果比较MyVar LIKE "tag(1###)<EX-->",则
MyVar可以是从"tag(1000)<EX-->""tag(1999)<EX-->"的任何

使用like运算符时,#-都是特殊字符。

要匹配文字字符#,请在其周围添加括号,如[#]

请参阅此处的完整文档:https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/like-operator

最新更新