Description
Returns the position of the first occurrence of one string within another.
Syntax
InStr([start,]string1,string2[,compare])
The InStr function syntax has these parts:
Part |
Description |
start |
Numeric expression that sets the starting position for each search. If omitted, search begins at the first character position. If start contains no valid data, an error occurs. Start is required if compare is specified. |
string1 |
String expression being searched. If string1 contains no valid data, Null is returned. |
string2 |
String expression sought. If string2 contains no valid data, Null is returned. |
compare |
Number specifying the type of string comparison. Specify 1 to perform a textual case-insensitive comparison. Specify 0 (default) to perform a binary comparison. If compare is Null, an error occurs. Start is required if compare is specified. If compare is omitted, the setting of Option Compare is used to determine the type of comparison. |
Return Values
Value |
Description |
0 |
string1 is zero-length. |
start |
string2 is zero-length. |
0 |
string2 not found. |
Position at which match is found |
string2 is found within string1. |
0 |
start > string2. |
Remarks
Note
When Option Compare Text is specified, comparisons are textual and case-insensitive. When Option Compare Binary is specified, comparisons are strictly binary.
Note
Another function (InStrB) is provided for use with the double-byte character sets (DBCS) used in some Asian locales. Instead of returning the character position of the first occurrence of one string within another, InStrB returns the byte position. In areas where DBCS is not used, InStrB behaves the same as InStr.
See Also
Option Compare Statement.
Example
This example uses the InStr function to return the position of the first occurrence of one string within another.
SearchString ="XXpXXpXXPXXP" ' String to search in. SearchChar = "P" ' Search for "P". ' A textual comparison starting at position 4. Returns 6. MyPos = InStr(4, SearchString, SearchChar, 1) ' A binary comparison starting at position 1. Returns 9. MyPos = InStr(1, SearchString, SearchChar, 0) ' Comparison is binary by default (if last argument is omitted). MyPos = InStr(SearchString, SearchChar) ' Returns 9. MyPos = InStr(1, SearchString, "W") ' Returns 0.