【发布时间】:2013-03-13 04:16:44
【问题描述】:
我想查找字符串中是否包含“,”(逗号)。除了逐个字符读取之外,我们还有其他选择吗?
【问题讨论】:
-
INSTR适合你吗?
我想查找字符串中是否包含“,”(逗号)。除了逐个字符读取之外,我们还有其他选择吗?
【问题讨论】:
INSTR 适合你吗?
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 的值。
请注意,在这种情况下,您必须指定起始位置,如我链接的规范中所述:如果指定了比较,则需要起始参数。
【讨论】:
也可以使用特殊词like:
Public Sub Search()
If "My Big String with, in the middle" Like "*,*" Then
Debug.Print ("Found ','")
End If
End Sub
【讨论】:
还有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。
【讨论】:
基于 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
【讨论】:
鉴于现有的 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
【讨论】: