I want to find if a string contains a ","(comma) in it. Do we have any other option other than reading char-by-char?
-
19Does `INSTR` work for you? – Stephen Quan Mar 23 '13 at 09:13
6 Answers
Use the Instr function (old version of MSDN doc found here)
Dim pos As Integer
pos = InStr("find the comma, in the string", ",")
will return 15 in pos
If not found it will return 0
If you need to find the comma with an excel formula you can use the =FIND(",";A1)
function.
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).
Dim posOf_A As Integer
posOf_A = InStr(1, "find the comma, in the string", "A", vbTextCompare)
will give you a value of 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.

- 41,474
- 78
- 114
- 152
-
6But what if the found string is in position 0? How do you distinguish between "found on index 0" and "not found (0)"? – gEdringer Aug 29 '16 at 13:50
-
18
You can also use the special word like
:
Public Sub Search()
If "My Big String with, in the middle" Like "*,*" Then
Debug.Print ("Found ','")
End If
End Sub

- 4,435
- 3
- 47
- 68
-
4Link to pattern format https://msdn.microsoft.com/en-us/library/swf8kaxw.aspx?f=255&MSPPError=-2147217396 – Matthew Lock Aug 30 '15 at 03:56
There is also the InStrRev function which does the same type of thing, but starts searching from the end of the text to the beginning.
Per @rene's answer...
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:
Dim pos As Integer
pos = InStrRev("find the comma, in the string", "the")
...would return 20 to pos, instead of 6.

- 6,613
- 3
- 41
- 60
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:
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

- 3,570
- 12
- 59
- 95
-
3What kind of a database error are we expecting in this function? The error trapping and the error message seem to be entirely pointless. – Roobie Nuby Dec 03 '14 at 07:30
-
12@RoobieNuby That's just my default error handling. I put it in on all my functions because if something goes wrong, I want the staff to call me, not to try and fix it themselves. – Sinister Beard Dec 03 '14 at 09:16
You wouldn't really want to do this given the existing Instr/InstrRev functions but there are times when it is handy to use EVALUATE to return the result of Excel worksheet functions within VBA
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

- 83,427
- 12
- 54
- 101
-
1Fyi - maybe interested in further late post getting also match positions :+) @Harr – T.M. Mar 15 '23 at 17:16
Just to complete the possibilities listed, I would like to demonstrate how you can use Split()
for an all-round function with the following variants depending on the optional argument n
passed:
- a) show whether a substring was found at all (-1 or omitted as default value)
- b) show how many substrings were found (0) ,
- c) show at which position the nth substring was found (1 .. n).
Function StrIncludes( _
ByVal s As String, _
Optional ByVal IncludeString As String = ",", _
Optional n As Long = -1 _
) As Long
'Purp.: find specified substring based on numeric value n
'Note : 2nd argument IncludeString is optional (default value is comma if omitted)
' 3rd argument n: -1~~>only boolean; 0~~>count(s); 1..n ~~>position
Dim tmp: tmp = Split(s, IncludeString)
StrIncludes = UBound(tmp) > 0 ' a) boolean return value indicating a found substring
Select Case n ' individual numeric values:
Case 0 ' b) return Count(s), not boolean value
StrIncludes = UBound(tmp)
Case 1
StrIncludes = IIf(StrIncludes, Len(tmp(n - 1)) + n, 0)
Case Is > 1 ' c) return Position of nth finding
If n > UBound(tmp) Then StrIncludes = 0: Exit Function
StrIncludes = IIf(StrIncludes, Len(tmp(0)) + n, 0)
Dim i As Long
For i = 2 To n: StrIncludes = StrIncludes + Len(tmp(i - 1)): Next
End Select
End Function
Example call
Sub ExampleCall()
' define base string
Dim s As String
s = "Take this example string, does it contain a comma, doesn't it?"
'a) check if base string contains indicated search string, e.g. a comma (default value)
Debug.Print "Is Found: " & CBool(StrIncludes(s)) ' ~~> Is Found: True
'b) get number of substrings
Debug.Print "Count(s): " & StrIncludes(s, , 0) ' ~~> Count(s): 2
'c) get position of nth substring
Debug.Print "~~~ Findings of nth substring ~~~ "
Dim n As Long
For n = 1 To 3
Debug.Print n & ordinalSuffix(n) & " substring at Pos.: " & StrIncludes(s, , n)
Next
End Sub
Function ordinalSuffix(ByVal number As Long) As String
Dim suffixes: suffixes = Split(" st nd rd th")
ordinalSuffix = suffixes(Abs(number))
End Function
Debugging results in immediate window
Is Found: Wahr
Count(s): 2
~~~ Findings of nth substring ~~~
1st substring at Pos.: 25
2nd substring at Pos.: 50
3rd substring at Pos.: 0 ' no finding at all

- 9,436
- 3
- 33
- 57