VBA code to read a character within a string

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:

  1. 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.

VBA_Macro_read_single_character_within_string

 

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;

  1. 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.

VBA-code-to-read-character

About the Author

SRINI S

A passionate blogger. Love to share solutions and best practices on wordpress hosting, issues and fixes, excel VBA macros and other apps