Excel VBA uses various built-in functions to handle strings. These string handling functions are Left, Right, Instr, Mid and Len . The following example illustrates the usage of all these functions.
InStr is a function that looks for and returns the position of a substring in a phrase
Private Sub cmdInstr_Click()
Dim phrase As String
phrase = Cells(1, 1).Value
Cells(4, 1) = InStr(phrase, "ual")
End Sub
The function InStr(phrase,"ual") will find the substring "ual" from the phrase "Visual Basic" entered in cells(1,1) and then return its position, in this case, it is 4 from the left.
Left is a function that extracts the characters from a phrase, starting from the left.
Left(phrase,4) means 4 characters are extracted from the phrase, starting from the leftmost position.
Private Sub cmdLeft_Click()
Dim phrase As String
phrase = Cells(1, 1).Value
Cells(2, 1) = Left(phrase, 4)
End Sub
This code returns the substring "Visu" from the phrase "Visual Basic" entered in cells(1,1)
Right is a function that extracts characters from a phrase, starting from the Right. Right(phrase,5) means 5 characters are extracted from the phrase, starting from the rightmost position.
Private Sub cmdRight_Click()
Dim phrase As String
phrase = Cells(1, 1).Value
Cells(3, 1) = Right(phrase, 5)
This code returns the substring "Basic" from the phrase "Visual Basic" entered in cells(1,1)
Mid is a function that extracts a substring from a phrase, starting from the position specified by the second parameter in the bracket.
Mid(phrase,8,3) means a substring of three characters are extracted from the phrase, starting from the 8th position from the left, including empty space.
<Private Sub cmdMid_Click()
Dim phrase As String
phrase = Cells(1, 1).Value
Cells(5, 1) = Mid(phrase, 8, 3)
End Sub
This code returns the substring "Bas" from the phrase "Visual Basic" entered in cells(1,1)
Len is a function that returns the length of a phrase(including empty space in between)
Private Sub cmdLen_Click()
Dim phrase As String
phrase = Cells(1, 1).Value
Cells(6, 1) = Len(phrase)
End Sub
The code returns 12 for the phrase "Visual Basic" entered in cells(1,1)
Figure 8.1
Copyright ® 2008 Dr.Liew Voon Kiong . All rights reserved [Privacy Policy]
Contact: Facebook Page