The Excel VBA InStrRev function returns an integer representing the position of a substring within a string. The Function searches the string from right to left (i.e. from the end to the start of the string).
If the substring is not found, the function returns the value 0.
The syntax of the InStrRev function is:
Where the function arguments are:
StringCheck | - | The string that you want to search. | |||||||||
StringMatch | - | The substring that you want to search for. | |||||||||
[Start] | - |
An optional integer argument, representing the position (from the start of StringCheck) that you want to start searching from. If omitted, the [Start] argument takes on the default value of -1, meaning that the search starts from the end of the string. |
|||||||||
[Compare] | - |
An optional argument representing the type of comparison to make. This can be any of the following values: |
|||||||||
|
|||||||||||
If omitted, the [Compare] argument takes on the default value vbBinaryCompare. |
' Example 1. Find the position of the last space (i.e. the substring " ") within the string
' "John Michael Paul Smith".
Dim pos As Integer
' This returns the result 18.
pos = InStrRev( "John Michael Paul Smith", " " ) |
In the example above:
' Example 2. Find the position of the last space that occurs within the string "John Michael
' Paul Smith" before character 17.
Dim pos As Integer
' This returns the result 13.
pos = InStrRev( "John Michael Paul Smith", " ", 17 ) |
In the example above, the search begins at position 17 of the string "John Michael Paul Smith" and so the function returns the space between the middle names "Michael" and "Paul". I.e. the space at position 13.
' Example 3. Find the position of the last and second to the last spaces within the string
' "John Michael Paul Smith".
Dim lastSpacePos As Integer
Dim secondLastSpacePos As Integer
lastSpacePos = InStrRev( "John Michael Paul Smith", " " )
' The variables lastSpacePos and secondLastSpacePos are now equal to 18 and 13 respectively.
secondLastSpacePos = InStrRev( "John Michael Paul Smith", " ", lastSpacePos - 1 ) |
In the example above:
' Example 4. Find the last occurrence of the text "ZZ" within the string "John Michael Paul Smith".
Dim pos As Integer
' The text "ZZ" is not found and so the function returns the value 0.
pos = InStrRev( "John Michael Paul Smith", "ZZ" ) |
In the above example, the sub-string "ZZ" is not found and so the InStrRev function returns the value 0.
Further details and examples of the VBA InStrRev function are provided on the Microsoft Developer Network.