Excel VBA Mid Function
VBA Mid Function: The Mid function in VBA returns a substring from within a supplied string.
Syntax
Mid (Str, Start, [Length])
Parameter
Str (required) -This parameter represents a string from which you want to extract the substring.
Start (required) – This parameter represents the substring start position.
Length (optional) – This parameter represents the length of the substring. It returns all characters from the Start position to the end of the string if this argument is omitted.
Return
This function returns a substring from within a supplied string.
Example 1
Sub MidFunction_Example1() 'fetching substring from the string "VBA is an easy programming language", 'starting from position 1, with length 26. Dim str As String str = Mid ("VBA is an easy programming language.", 1, 26) ' it will return the text string "Michael". Cells(1, 1).Value = str End Sub
Output
VBA is an easy programming
Example 2
Sub MidFunction_Example2() 'fetching substring from the string "VBA is an easy programming language", Dim str As String 'start should be >0 Start = 0 str = Mid("VBA is an easy programming language.", Start) ' it will throw run time error as start is initialized as 0. Cells(1, 1).Value = str End Sub
Output