VBA Function: InStr
The VBA InStr function returns an integer value corresponding to the first position of a value found within a string (or the value 0 if no match is found).
Usage:
InStr(start_num, text, value)
or
InStr(start_num, text, value, compare)
Examples of Usage
Using the InStr function to determine the position of the word excel (starting the search from character 1 of the text):
Sub example()
website = "www.excel-pratique.com"
'Position of "excel" in the website
number = InStr(1, website, "excel")
MsgBox number 'Returns: 5
End Sub
Using the InStr function to determine the position of the word EXCEL (adding the value 1 as the fourth argument to ignore case):
Sub example()
website = "www.excel-pratique.com"
'Position of "EXCEL" in the website (ignoring case)
number = InStr(1, website, "EXCEL", 1)
MsgBox number 'Returns: 5
End Sub
Checking if a Text Contains a Value
The InStr function can also be used to determine whether the text contains the searched string or not:
Sub example()
website = "www.excel-pratique.com"
If InStr(1, website, "excel") > 0 Then
MsgBox "Yes!"
End If
End Sub
In this example, if a position is found, a number greater than 0 is returned by the function and the message box is displayed.