253

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

4

5 回答 5

419

使用Instr函数(旧版 MSDN 文档可在此处找到)

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 的值。

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

于 2013-03-23T09:13:09.573 回答
76

您还可以使用特殊词like

Public Sub Search()
  If "My Big String with, in the middle" Like "*,*" Then
    Debug.Print ("Found ','")
  End If
End Sub
于 2015-03-12T19:48:48.573 回答
23

还有一个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。

于 2014-07-14T17:03:24.553 回答
18

基于 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
于 2014-08-07T13:17:32.427 回答
1

鉴于现有的 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
于 2021-01-03T08:46:55.300 回答