Get Substring Position Method
The Get Substring Position method returns the position of the first occurrence of a substring that resides in another string. It can also return the following values:
Returns a zero in the following situations:
The value in the start argument is greater than the length of the value in the string2 argument.
The string1 argument contains a null string.
The string2 argument is not found.
If the string1 argument or the string2 argument contains a null variant, then it returns a null variant.
If the string2 argument contains a null string (""), then it returns the value of the start argument.
Format A
InStr([start,] string1, string2)
InStr(start, string1, string2[, compare])
Arguments can be of any type. This method converts them to strings.
The following table describes the arguments that you can use with this method.
Argument | Description |
---|---|
start |
An integer that identifies a position in the string that the string1 argument identifies. This position is the starting position, with the first character in the string as 1. If you do not specify a value for the start argument, then this method starts at the beginning of the string. |
string1 |
The string that includes the substring. |
string2 |
The substring. |
compare |
You can use one of the following values:
If you do not include the compare argument, then this method uses the module level default that the Set String Comparison method sets. For more information, see Set String Comparison Method. |
Example
The following example creates a random string of characters, and then uses the Get Substring Position method to find the position of a single character in that string:
Sub Button_Click
Dim x as Integer
Dim y
Dim str1 as String
Dim str2 as String
Dim letter as String
Dim randomvalue
Dim upper, lower
Dim position as Integer
Dim msgtext, newline
upper = Asc("z")
lower = Asc("a")
newline = Chr(10)
Randomize
For x = 1 to 26
randomvalue = Int(((upper - (lower + 1)) * Rnd) + lower)
letter = Chr(randomvalue)
str1 = str1 & letter
'Need to waste time here for fast processors
For y = 1 to 1000
Next y
Next x
str2 = "i"
position = InStr(str1,str2)
If position then
msgtext = "The position of " & str2 & " is: " _
& position & newline & "in string: " & str1
Else
msgtext = "The letter: " & str2 & " was not found in: " _
& newline
msgtext = msgtext & str1
End If
End Sub