【问题标题】:Check if a string contains another string检查一个字符串是否包含另一个字符串
【发布时间】:2013-03-13 04:16:44
【问题描述】:

我想查找字符串中是否包含“,”(逗号)。除了逐个字符读取之外,我们还有其他选择吗?

【问题讨论】:

  • INSTR 适合你吗?

标签: string vba


【解决方案1】:

使用Instr函数(旧版MSDN文档找到here

Dim pos As Integer

pos = InStr("find the comma, in the string", ",")

将在 pos 中返回 15

如果没有找到,它将返回 0

如果您需要使用 excel 公式查找逗号,您可以使用 =FIND(",";A1) 函数。

请注意,如果您想使用 Instr 来查找不区分大小写的字符串的位置,请使用 Instr 的第三个参数并将其指定为 const vbTextCompare(或者只为顽固分子设置 1)。

Dim posOf_A As Integer

posOf_A = InStr(1, "find the comma, in the string", "A", vbTextCompare)

会给你一个 14 的值。

请注意,在这种情况下,您必须指定起始位置,如我链接的规范中所述:如果指定了比较,则需要起始参数。

【讨论】:

  • 但是如果找到的字符串在位置 0 怎么办?如何区分“在索引 0 上找到”和“未找到 (0)”?
  • @gEdringer。当要找到的字符串位于开头时,它返回 1。
  • 文档移至此处:InStr
【解决方案2】:

也可以使用特殊词like

Public Sub Search()
  If "My Big String with, in the middle" Like "*,*" Then
    Debug.Print ("Found ','")
  End If
End Sub

【讨论】:

【解决方案3】:

还有InStrRev 函数,它执行相同类型的操作,但从文本末尾开始搜索。

根据@rene 的回答...

Dim pos As Integer
pos = InStrRev("find the comma, in the string", ",")

...仍然会返回 15 到 pos,但是如果字符串有多个搜索字符串,比如单词“the”,那么:

Dim pos As Integer
pos = InStrRev("find the comma, in the string", "the")

...将 20 返回到 pos,而不是 6。

【讨论】:

    【解决方案4】:

    基于 Rene 的回答,您还可以编写一个函数,如果子字符串存在则返回 TRUE,如果不存在则返回 FALSE:

    Public Function Contains(strBaseString As String, strSearchTerm As String) As Boolean
    'Purpose: Returns TRUE if one string exists within another
    On Error GoTo ErrorMessage
        Contains = InStr(strBaseString, strSearchTerm)
    Exit Function
    ErrorMessage:
    MsgBox "The database has generated an error. Please contact the database administrator, quoting the following error message: '" & Err.Description & "'", vbCritical, "Database Error"
    End
    End Function
    

    【讨论】:

    • 我们期望在这个函数中出现什么样的数据库错误?错误捕获和错误消息似乎完全没有意义。
    • @RoobieNuby 这只是我的默认错误处理。我把它放在我所有的功能中,因为如果出现问题,我希望工作人员给我打电话,而不是自己尝试修复。
    【解决方案5】:

    鉴于现有的 Instr/InstrRev 函数,您不会真的想这样做,但有时使用 EVALUATE 在 VBA 中返回 Excel 工作表函数的结果很方便

    Option Explicit
    
    Public Sub test()
    
        Debug.Print ContainsSubString("bc", "abc,d")
    
    End Sub
    Public Function ContainsSubString(ByVal substring As String, ByVal testString As String) As Boolean
        'substring = string to test for; testString = string to search
        ContainsSubString = Evaluate("=ISNUMBER(FIND(" & Chr$(34) & substring & Chr$(34) & ", " & Chr$(34) & testString & Chr$(34) & "))")
    
    End Function
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多