检查字符串是否包含另一个字符串

kri*_*hna 220 string vba

我想找一个字符串是否包含","(逗号).除了阅读char-by-char之外,我们还有其他选择吗?

ren*_*ene 363

使用Instr功能

Dim pos As Integer

pos = InStr("find the comma, in the string", ",")
Run Code Online (Sandbox Code Playgroud)

将返回15 in pos

如果没有找到它将返回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)
Run Code Online (Sandbox Code Playgroud)

会给你14的价值.

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

  • @gEdringer.当要找到的字符串在开始时它返回1. (9认同)
  • 但是,如果找到的字符串位于0位置怎么办?你如何区分"在索引0上找到"和"未找到(0)"? (4认同)

Mak*_*kah 62

您还可以使用特殊字词like:

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

  • 链接到模式格式https://msdn.microsoft.com/en-us/library/swf8kaxw.aspx?f=255&MSPPError=-2147217396 (3认同)

Lim*_*awk 22

还有InStrRev函数可以执行相同类型的操作,但是从文本末尾开始搜索到开头.

Per @rene的答案......

Dim pos As Integer
pos = InStrRev("find the comma, in the string", ",")
Run Code Online (Sandbox Code Playgroud)

...仍然会返回15到pos,但如果字符串有多个搜索字符串,就像单词"the",那么:

Dim pos As Integer
pos = InStrRev("find the comma, in the string", "the")
Run Code Online (Sandbox Code Playgroud)

...将返回20而不是6.


Sin*_*ard 15

在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
Run Code Online (Sandbox Code Playgroud)

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