我想知道一个字符串中是否包含一个“,”(逗号)。除了逐字符读取,我们还有其他选择吗?
使用Instr函数(旧版MSDN文档在这里找到)
Dim pos As Integer
pos = InStr("find the comma, in the string", ",")
将返回15在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)
得到的值是14。
请注意,在这种情况下,您必须指定开始位置,正如我链接的规范所述:如果指定了compare,则需要start参数。
还有一个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
你也可以用特殊的词,比如:
Public Sub Search()
If "My Big String with, in the middle" Like "*,*" Then
Debug.Print ("Found ','")
End If
End Sub
你不会真的想这样做,因为现有的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
推荐文章
- 如何删除表中特定列的第一个字符?
- 我应该如何从字符串中删除所有的前导空格?- - - - - -斯威夫特
- 将整数转换为字符串,以逗号表示千
- 将JavaScript字符串中的多个空格替换为单个空格
- printf()和puts()在C语言中的区别是什么?
- jQuery -替换字符串中某个字符的所有实例
- Base64长度计算?
- 使用split("|")按管道符号拆分Java字符串
- Std::cin输入空格?
- 我如何在c++中创建一个随机的字母数字字符串?
- 如何使用JavaScript大写字符串中每个单词的第一个字母?
- Java中的split()方法对点(.)不起作用。
- 我如何检查如果一个变量是JavaScript字符串?
- 如何显示有两个小数点后的浮点数?
- 在Lua中拆分字符串?