VBA code to read a character within a string.
Case 1:
Suppose the string is “ Excel VBA macro”, and you want to read a character before BA (i.e. V) within that string.
VBA code:
-
Sub readCharWithinString() Dim inputStr Dim charac inputStr = "Excel VBA macro" charac = Mid(inputStr, 7, 1) MsgBox ("The character is " & charac) End Sub
When you run above macro, below message box is displayed.
Case 2:
Suppose the string is too long and you want to find a sub string within the string and read the character before that sub string.
Let’s take string “Excel VBA macro to read character within String or a text file-line” and you want to read character before “line” sub string.
VBA code;
-
Sub readCharWithinString() Dim inputStr Dim charac Dim subStr inputStr = "Excel VBA macro to read character within String or a text file-line" subStr = InStr(inputStr, "line") ' to find subString position within the string charac = Mid(inputStr, subStr - 1, 1) ' reading character just before "line" string MsgBox ("The character is " & charac) ' displaying the extracted character End Sub
When you run above macro, below message box is displayed.