【问题标题】:Two strings check true for equal but check false for Like operator两个字符串为相等检查 true,但为 Like 运算符检查 false
【发布时间】:2019-11-04 15:54:52
【问题描述】:

为什么“Like”语句不起作用?

“=”语句检查为真,但“like”运算符检查为假,为什么?

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

【问题讨论】:

  • 对不起...单元格(2,2)。值是“标签(1###)
  • # 表示使用Like时的单个数字。
  • # 是 like 运算符中的特殊字符,代表任何单个数字。因此是假值。将它们括在括号中以逃避其目的
  • 因为字面量# 不是数字。
  • 将其归结为一个非常的小例子,并在即时窗口? "#" Like "#" 中进一步解释我之前的评论。结果是False。要获取True,请添加括号:? "#" Like "[#]"

标签: excel vba vb-like-operator


【解决方案1】:

你用错了Like operator# 代表一个数字。

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

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###)&lt;EX--&gt;" 那么
MyVar 可以是从 "tag(1000)&lt;EX--&gt;""tag(1999)&lt;EX--&gt;" 的任何东西

【讨论】:

    【解决方案2】:

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

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

    在此处查看完整文档:https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/like-operator

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-30
      • 2019-08-29
      • 1970-01-01
      • 2016-01-30
      • 2018-06-08
      • 2018-06-07
      • 2012-10-15
      • 2014-04-17
      相关资源
      最近更新 更多