InStr function
Returns the position of the first occurrence of a string in another string.
InStr([start, ]string1, string2[, compare])
Parameters
Start
Options available. A numeric expression that sets the starting position for each search. If omitted, the search begins at the position of the first character. If start contains Null, an error occurs. If you have specified compare, you must have the start argument.
String1
Required option. The string expression that accepts the search.
string2
Required option. The string expression to search for.
Compare
Options available. Indicates the numeric value of the comparison type to use when calculating the substring. For numeric values, see the "Settings" section. If omitted, a binary comparison is performed.
Set up
The compare parameter can have the following values:
Constants |
value |
Description |
Vbbinarycompare |
0 |
Performs a binary comparison. |
vbTextCompare |
1 |
Performs a text comparison. |
return value
The InStr function returns the following values:
if |
InStr return |
String1 is zero length |
0 |
String1 is Null |
Null |
string2 is zero length |
Start |
String2 is Null |
Null |
String2 didn't find it. |
0 |
Find string2 in string1. |
Find the location of the matching string |
Start > Len (string2) |
0 |
Description
The following example uses InStr to search for strings:
Dim SearchString, SearchChar, MyPosSearchString ="XXpXXpXXPXXP" ' String to search in.SearchChar = "P" ' Search for "P".MyPos = Instr(4, SearchString, SearchChar, 1)
' A textual comparison starting at position 4. Returns 6.
MyPos = Instr(1, SearchString, SearchChar, 0)
' A binary comparison starting at position 1. Returns 9.
MyPos = Instr(SearchString, SearchChar)
' Comparison is binary by default (last argument is omitted). Returns 9.
MyPos = Instr(1, SearchString, "W")
' A binary comparison starting at position 1. Returns 0 ("W" is not found).
Attention The InStrB function uses the byte data contained in the string, so InStrB returns not the character position where the string first appears in another string, but the byte position.