Professional Documents
Culture Documents
Examples
Home>>
Blog>>
Excel VBA Tips & Tricks
>>Excel VBA InStr Function – Explained with Examples
She wanted to know how to apply bold font format to a specific part of a
string within a cell. For example, apply the bold format to only the word
‘Hello’ from ‘Hello World’.
But first, let’s see how the Excel VBA InStr function works!
For example, if you want to find the position of ‘x’ in ‘Excel’, using the Excel
VBA InStr function would return 2.
If the InStr function can not find the substring within the main string,
it would return 0.
Now let’s have a look at some example of using the Excel VBA InStr Function
Sub FindFromBeginning()
MsgBox Position
End Sub
When you run this code, it will show a message box with the value 7, which
is the position of ‘V’ in the string ‘Excel VBA’.
Example 2 – Finding the Position from the
beginning of the Second Word
Suppose, I want to find the position of ‘the’ in the sentence – ‘The quick
brown fox jumps over the lazy dog’
Sub FindFromSecondWord()
Position = InStr(4, "The quick brown fox jumps over the lazy dog", "the", vbBinaryCompare)
MsgBox Position
End Sub
This code will show the message box with the value 32 as we have specified
the starting position as 4. Hence it ignores the first ‘The’ and finds the
second ‘the’ in the sentence.
If you want to make it more dynamic, you can enhance the code so that it
automatically ignore the first word.
Sub FindFromSecondWord()
StartingPosition = InStr(1, "The quick brown fox jumps over the lazy dog", " ", vbBinaryCompare)
Position = InStr(StartingPosition, "The quick brown fox jumps over the lazy dog", "the",
vbBinaryCompare)
MsgBox Position
End Sub
This code first finds the position of a space character and stores it in the
variable StartingPosition.
It then uses this variable as the starting position to look for the word ‘the’.
Hence it returns 32 (which is the starting position of ‘the’ after the first
word).
FindPosition = Position
End Function
Now you can use this custom function as any other worksheet function. It
will take a cell reference as input and give you the position of @ in it.
Similarly, you can create a custom function to find the position of any
substring within the main string.
Sub Bold()
Dim rCell As Range
CharCount = Len(rCell)
Next rCell
End Sub
The above code uses the For Each loop to go through each of the cells in the
selection. It identifies the position of the opening bracket character using
the InStr function. It then changes the font of the text before the bracket.
To use this code, you need to copy and paste in a module in the VB editor.