VBA - 检查字符串中是否存在“逗号”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44134947/
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
VBA - Check if "Comma" exists in a string or not
提问by MMS
I am looking to see if a string has a comma or not.
我想看看一个字符串是否有逗号。
Lets say I have two usernames "David , Boon" and "David Blind".
假设我有两个用户名“David , Boon”和“David Blind”。
I need to write an if loop based on the conditions whether ',' exists in the User name or not. Is there a way to check that ? Something like Contains in .Net
我需要根据用户名中是否存在“,”的条件编写一个 if 循环。有没有办法检查?类似于 .Net 中的包含
Kindly share your thoughts.
请分享您的想法。
回答by ThunderFrame
You can use the InStr
function to check the presence/location of one string within another:
您可以使用该InStr
函数来检查一个字符串在另一个字符串中的存在/位置:
Dim myVar As String
myVar = "foo,bar"
If InStr(1, myVar, ",") > 0 Then
'There was a comma
End If
回答by ThunderFrame
Here's two,
这里有两个,
if cbool(instr(1, mystring, chr(44))) then
...
if cbool(ubound(split(mystring, chr(44)))) then
...
回答by Subodh Tiwari sktneer
You may try the following approach in your code...
您可以在代码中尝试以下方法...
If InStr(Range("A1").Value, ",") Then
MsgBox "Comma Exists", vbInformation
Else
MsgBox "No comma exists", vbExclamation
End If
Or just have a Function like below...
或者只是有一个像下面这样的功能......
Function CommaExists(ByVal Rng As Range) As Boolean
If InStr(Rng.Value, ",") Then
CommaExists = True
End If
End Function
And call the function in your sub routine like this...
并像这样在您的子例程中调用该函数...
Sub Test()
If CommaExists(Range("A1")) Then
MsgBox "Comma found in the string.", vbInformation
Else
MsgBox "No Comma found in the string.", vbExclamation
End If
End Sub