Check if a string contains another string
我想查找字符串中是否包含","(逗号)。除了按字符读取字符以外,我们还有其他选择吗?
使用Instr函数
1 2 3 | Dim pos As Integer pos = InStr("find the comma, in the string",",") |
将在pos中返回15
如果找不到,它将返回0
如果需要使用excel公式查找逗号,则可以使用
请注意,如果要使用
1 2 3 | Dim posOf_A As Integer posOf_A = InStr(1,"find the comma, in the string","A", vbTextCompare) |
的值为14。
请注意,在这种情况下,您必须按照我链接的规范中的说明指定开始位置:如果指定了compare,则必须使用start参数。
您也可以使用特殊词
1 2 3 4 5 | Public Sub Search() If"My Big String with, in the middle" Like"*,*" Then Debug.Print ("Found ','") End If End Sub |
还有InStrRev函数,它执行相同类型的操作,但从文本的末尾开始搜索。
每个@rene的答案...
1 2 | Dim pos As Integer pos = InStrRev("find the comma, in the string",",") |
...仍将返回15到pos,但是如果该字符串包含多个搜索字符串之一,例如单词" the",则:
1 2 | Dim pos As Integer pos = InStrRev("find the comma, in the string","the") |
...将返回20到pos,而不是6。
基于Rene的答案,您还可以编写一个函数,如果存在子字符串,则返回TRUE,否则返回FALSE:
1 2 3 4 5 6 7 8 9 | 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 |
鉴于现有的Instr / InstrRev函数,您实际上并不想这样做,但是有时很方便地使用EVALUATE返回VBA中Excel工作表函数的结果。
1 2 3 4 5 6 7 8 9 10 11 12 | 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 |