VBA Mid Function

Related Functions:
VBA Left
VBA Right

Description

The VBA Mid function returns a substring from within a supplied string. The user specifies the start position and length of the substring.

The syntax of the VBA Mid function is:

Mid( Str, Start, [Length] )

Where the function arguments are:

Str-The original string that you want to extract a substring from.
Start-The substring start position.
[Length]-

An optional argument representing the length of the substring.

If the [Length] argument is omitted, the Mid function returns all characters from the Start position to the end of the string.


VBA Mid Function Examples

Example 1

' Example 1. Extract a substring from the string "John Michael Smith", starting from position 6, with length 7.
Dim res As String
res = Mid( "John Michael Smith", 6, 7 )
' The variable res is now equal to the text string "Michael".

In the example above, the VBA Mid function returns the result "Michael".


Example 2

' Example 2. Extract the last part of the string "John Michael Smith", starting from position 14.
Dim res As String
res = Mid( "John Michael Smith", 14 )
' The variable res is now equal to the text string "Smith".

In the example above, the [Length] argument is omitted and so the VBA Mid function returns all characters from the supplied Start position to the end of the string. Therefore, the function returns the substring "Smith".


Further information and examples of the VBA Mid function are provided on the Microsoft Developer Network.