By using expertatexcel.com you agree to our cookie policy, We and our partners operate globally and use cookies, for multiple purposes

Become an Σxpert at Σxcel.com

 


instr( ) - find a string within a string and return the offset

🔝The InStr( ) function is a highly used function to find the location of one string within another.

Immediate Window


s = "abcdefg"
? InStr(s,"d")
4
? Instr(s,"h")
0
? InStr(s,"fg")
6




There is an optional starting point.

Immediate Window


s = "abcdefgabcdefg"
? InStr(3,s,"ab")
8



In the above, the first parameter is 3 which says to start the search from the 3rd position offset from 1st. Note that in many language the first character is considered position 0.

Some common usage:

If Instr(s,"value") > 0 then
   ' exists
Elseif Instr(s,"value") = 0 then
   ' string doesn't exist
End If

This Function is often used with the Mid function.

There is a final parameter that tells the InStr( ) function what type of comparison to do

ConstantValueDescription
vbUseCompareOption -1Performs a comparison by using the setting of the Option Compare statement.
vbBinaryCompare0Performs a binary comparison.
vbTextCompare1Performs a textual comparison.


Immediate Window

s = "abcdefg"
? InStr(s,"d",1) ' the default
4
? InStr(s,"D")
0

? InStr(s,"D",vbTextCompare)
4





See Also
  • Bing VBA Instr

  •