vba 检查一个字符串是否包含另一个字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15585058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if a string contains another string
提问by krishna
I want to find if a string contains a ","(comma) in it. Do we have any other option other than reading char-by-char?
我想查找字符串中是否包含“,”(逗号)。除了逐个字符读取之外,我们还有其他选择吗?
回答by rene
Use the Instrfunction
使用Instr函数
Dim pos As Integer
pos = InStr("find the comma, in the string", ",")
will return 15 in pos
将在 pos 中返回 15
If not found it will return 0
如果没有找到,它将返回 0
If you need to find the comma with an excel formula you can use the =FIND(",";A1)
function.
如果您需要使用 excel 公式查找逗号,您可以使用该=FIND(",";A1)
函数。
Notice that if you want to use Instr
to find the position of a string case-insensitive use the third parameter of Instr and give it the const vbTextCompare
(or just 1 for die-hards).
请注意,如果您想使用Instr
不区分大小写的字符串来查找位置,请使用 Instr 的第三个参数并为其指定 const vbTextCompare
(对于顽固的人,则仅为 1)。
Dim posOf_A As Integer
posOf_A = InStr(1, "find the comma, in the string", "A", vbTextCompare)
will give you a value of 14.
会给你一个 14 的值。
Note that you have to specify the start position in this case as stated in the specification I linked: The start argument is required if compare is specified.
请注意,在这种情况下,您必须按照我链接的规范中的说明指定开始位置:如果指定了比较,则需要开始参数。
回答by Makah
You can also use the special word like
:
您还可以使用特殊词like
:
Public Sub Search()
If "My Big String with, in the middle" Like "*,*" Then
Debug.Print ("Found ','")
End If
End Sub
回答by LimaNightHawk
There is also the InStrRevfunction which does the same type of thing, but starts searching from the end of the text to the beginning.
还有InStrRev函数执行相同类型的操作,但从文本的末尾开始搜索。
Per @rene's answer...
根据@rene 的回答...
Dim pos As Integer
pos = InStrRev("find the comma, in the string", ",")
...would still return 15 to pos, but if the string has more than one of the search string, like the word "the", then:
...仍会返回 15 给 pos,但如果字符串包含多个搜索字符串,例如单词“the”,则:
Dim pos As Integer
pos = InStrRev("find the comma, in the string", "the")
...would return 20 to pos, instead of 6.
...将返回 20 到 pos,而不是 6。
回答by Sinister Beard
Building on Rene's answer, you could also write a function that returned either TRUE if the substring was present, or FALSE if it wasn't:
基于 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