How to use Mid function in VBA?

In VBA (Visual Basic for Applications), the Mid function is used to extract a substring from a larger string, starting at a certain position and optionally for a certain length. The syntax for the Mid function in VBA is as follows:

Mid(string, start, [length])
Parameters: string is the original string from which you want to extract the substring. start is the starting position from which the extraction should begin (1-based index). [length] is optional and determines the number of characters to extract. If omitted, the function extracts all characters from the start position to the end of the string. Here’s an example of how to use the Mid function in VBA:

Sub ExampleMidFunction()
    Dim originalString As String
    Dim result As String
    Dim startPosition As Integer
    Dim numberOfCharacters As Integer
    
    originalString = "Hello, World!"
    startPosition = 8
    numberOfCharacters = 5
    
    ' Extract a substring from the 8th character, 5 characters long
    result = Mid(originalString, startPosition, numberOfCharacters)
    
    ' The result will be "World"
    MsgBox result
End Sub
If you want to extract characters from the start position to the end of the string, just omit the length parameter:

Sub ExampleMidToEnd()
    Dim originalString As String
    Dim result As String
    Dim startPosition As Integer
    
    originalString = "Hello, World!"
    startPosition = 8
    
    ' Extract from the 8th character to the end of the string
    result = Mid(originalString, startPosition)
    
    ' The result will be "World!"
    MsgBox result
End Sub
Please note that in VBA, string indices are 1-based, not 0-based as in many other programming languages.

Unlock Your Potential

Excel

Basic - Advanced

Access

Access Basic - Advanced

Power BI

Power BI Basic - Advanced

Help us grow the project

Leave a Reply

Your email address will not be published. Required fields are marked *