InStr function
Returns the location where a string first appears in another string.
InStr([start, ]string1, string2[, compare])
parameter
start
Optional. Numeric expressions that set the start position of each search. If omitted, a search will start from the position of the first character. ifstartIf Null is included, an error will appear. If specifiedcompare, there must bestartparameter.
string1
Required option. A string expression that accepts searches.
string2
Required option. The string expression to search for.
compare
Optional. Indicates the value of the comparison type used when calculating the substring. For values, see the Settings section. If omitted, a binary comparison will be performed.
set up
compareThe parameters can have the following values:
constant | value | describe |
---|---|---|
vbBinaryCompare | 0 | Perform binary comparison. |
vbTextCompare | 1 | Perform text comparison. |
Return value
InStrThe 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 not found | 0 |
Find string2 in string1 | Find the location of the matching string |
start > Len(string2) | 0 |
illustrate
The following example usesInStrSearch string:
Dim SearchString, SearchChar, MyPosSearchString ="XXpXXpXXPXXP" ' String to search = "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).
Notice InStrBThe function uses byte data contained in the string, soInStrBWhat is returned is not the character position where a string first appears in another string, but the byte position.