VBA – 检查string中是否存在“逗号”
我期待看看一个string是否有逗号。
假设我有两个用户名“David,Boon”和“David Blind”。
我需要根据用户名是否存在','的条件编写一个if循环。 有没有办法来检查? 类似于包含在.Net中
请分享你的想法。
您可以使用InStr
函数来检查另一个string的存在/位置:
Dim myVar As String myVar = "foo,bar" If InStr(1, myVar, ",") > 0 Then 'There was a comma End If
这里有两个,
if cbool(instr(1, mystring, chr(44))) then ... if cbool(ubound(split(mystring, chr(44)))) then ...
您可以在代码中尝试以下方法…
If InStr(Range("A1").Value, ",") Then MsgBox "Comma Exists", vbInformation Else MsgBox "No comma exists", vbExclamation End If
或者只是有一个像下面的function…
Function CommaExists(ByVal Rng As Range) As Boolean If InStr(Rng.Value, ",") Then CommaExists = True End If End Function
并像这样调用你的子程序中的function…
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
我认为这里最可读的选项(主观意见,但值得一提)是一个Like
运算符:
Dim myVar As String myVar = "foo,bar" If myVar Like "*,*" Then 'There was a comma End If