Learn about VBA Instr Function
In This Article, we will learn about following topic of InStr function in Excel VBA with Practical Example.
1.Introduction of InStr Functino
2. VBA code for Basic understanding
3. VBA Code for Case-Sensitive Search
4. VBA Code for Conditional Logic
5. VBA Code for Count How Many Times a Substring Appears
Introduction
The InStr function in VBA is used to search for the occurrence of one string (substring) within another string. It returns the position (as an integer) where the substring is first found. If the substring is not found, the function returns 0
The InStr function in VBA is a search tool that helps find the location of a specific text (substring) within a larger text (main string). Think of it as a way to ask, “Where does this word or character appear in this sentence?”
Syntax
InStr([start], string1, string2, [compare])
Parameters
- start (Optional):
- The position in string1 where the search begins. The default is 1 (start of the string).
- If omitted, the search starts from the beginning of string1.
- string1:
- The string to be searched.
- string2:
- The substring to find within string1.
- compare (Optional):
- Specifies the type of comparison.
- Options:
- vbBinaryCompare (Default): Performs a case-sensitive search.
- vbTextCompare: Performs a case-insensitive search.
- vbDatabaseCompare: Available only in Microsoft Access (compares based on the database locale).
Return Value
- Integer:
- Position of the first occurrence of string2 in string1.
- Returns 0 if string2 is not found.
Example
- Basic use
VBA Code:
Sub InStrExample() Dim position As Integer position = InStr("Hello World", "World") MsgBox position ' Output: 7 (Position where "World" starts) End Sub
- Case SenSetive Search (default)
VBA Code
Sub InStrExample() Dim position As Integer position = InStr("Hello World", "world") ' in this searching word is mentioned in small letter so due to erro MsgBox position ' Output: 0 (due to small letter of "world") End Sub
2. Case-Sensitive Search
VBA Code
Sub InStrExample_3() Dim position As Integer position = InStr("Hello World", "world", vbTextCompare) MsgBox position 'Output: 10 (due to use of bianary word : vbTextCompare, if search is in small letter, result will be accurate) End Sub
3. Specify Start Position
VBA Code:
Sub instrExample_4() Dim position As Integer position = InStr(8, "hello miss hello", "hello") MsgBox position 'hello start at the position 12 End Sub
4. Using Instr with Conditional Logic
VBA Code
Sub usinginstrconditional() Dim text As String text = "VBA is Powerful" If InStr(text, "Powerful") > 0 Then MsgBox "Ther word powerful find" Else MsgBox "The Word not find" End If End Sub
5. Extract Text After a Specific Character
Suppose you have “Name: John” and want to extract “John”:
VBA Code
Sub Extract1() Dim fulltext As String Dim result As String fulltext = "Name:John" Dim position As Integer position = InStr(fulltext, ":") If position > 0 Then result = Mid(fulltext, position) MsgBox result Else MsgBox "Colon not found" End If End Sub
6. Count How Many Times a Substring Appears
Find how many times “apple” appears in a sentence:
VBA Code:
Sub CountOccurrences() Dim text As String Dim position As Integer Dim count As Integer text = "apple orange apple banana apple" position = 0 count = 0 Do position = InStr(position + 1, text, "apple") ' Find "apple" starting from the next position If position > 0 Then count = count + 1 Loop Until position = 0 MsgBox "The word 'apple' appears " & count & " times." End Sub
Best Practices
- Always specify the compare parameter if the case-sensitivity of the search is critical.
- Use the start parameter to limit the search range for better performance on large strings.
- Combine with functions like Mid or Left for more complex string manipulations.
Key Points to Remember
- Case-Sensitivity:
- By default, InStr is case-sensitive unless you specify vbTextCompare.
- Zero-Based Indexing:
- Unlike some languages, VBA uses 1-based indexing. Position 1 is the first character.
- Error Handling:
- Ensure your code handles cases where InStr returns 0 (substring not found).
By mastering the InStr function, you can efficiently search and manipulate text data in Excel VBA.
Summary
- The InStr function is a powerful tool for finding and manipulating text in VBA.
- Use it to locate text, verify existence, and work with substrings.
- By combining it with other functions like Mid, Left, and Right, you can handle advanced string operations effectively.
Other topic to Read
- VBA String Functions : Excel VBA provides a variety of string functions that help manipulate and analyze text.
- VBA Functions : VBA (Visual Basic for Applications) functions are used to perform operations in Microsoft Office applications like Excel, Access, and Word. These functions can be built-in or user-defined
- VBA If Then Else : The If…Then…Else statement in VBA is used to execute different blocks of code based on whether a condition is True or False. It is one of the fundamental control structures used to introduce conditional logic into your code, allowing different actions to be taken depending on the values of variables or expressions
- VBA Do While Loop : A Do…While loop is used when we want to repeat a set of statements as long as the condition is true. The condition may be checked at the beginning of the loop or at the end of the loop.
5. Instr Function: Returns a Variant (Long) specifying the position of the first occurrence of one string within another