In VBA (Visual Basic for Applications), the Instr function is used to find the position of one string within another string. It returns the starting index of the first occurrence of the search string within the main string.
Syntax:
Instr([searchString], [mainString])
Parameters:
searchString(required): The string to search for.mainString(required): The string in which to search for thesearchString.
Return Value:
- Returns the starting index of the
searchStringinmainString, or0if the string is not found.
Example:
Dim startPos As Long
startPos = Instr("Hello, world!", "world")
Debug.Print startPos ' Output: 7
This will return 7, which is the starting index of the substring "world" in "Hello, world!".
Notes:
- If
searchStringis empty,Instrreturns0. - If
mainStringis empty,Instrreturns0. - If
searchStringis longer thanmainString, it returns0.
Common Use Cases:
- Finding the position of a substring.
- Checking if a substring exists in a string.
- Used in string manipulation or data validation.
Example with Instr and InstrRev:
Dim startPos As Long
startPos = Instr("Hello, world!", "w")
Debug.Print startPos ' Output: 3
startPos = InstrRev("Hello, world!", "w")
Debug.Print startPos ' Output: 3
Summary:
Instris used to find the starting index of a substring in a string.- It returns
0if the substring is not found. - It is commonly used in VBA for string operations.
Let me know if you want to use it in a specific context or with a custom example!