Mid
The Mid Function extracts a portion of a string from Str.
Note: To determine the number of characters in a string, use the Len function.
The Str argument can be any valid string expression. If Str contains Null, Null is returned.
The required Num argument is a Long numeric expression that sets the starting position for the extraction. If Num is greater than the number of characters in string, Mid returns a zero-length string ("").
The optional Len argument is a Variant containing a Long data type representing the number of characters to return. If omitted or if there are fewer than Len characters in Str (including the character at position Num ), all characters from the Num position to the end of the string are returned.
Syntax
Mid(Str, Num, Len)
Str:
A string or expression that can represent a valid text value. If Str contains Null, Null is returned.
Num:
A Long numeric expression that sets the starting position for the extraction. If Num is greater than the number of characters in string, Mid returns a zero-length string ("").
Len:
A Variant containing a Long data type representing the number of characters to return. If omitted or if there are fewer than Len characters in Str (including the character at position Num ), all characters from the Num position to the end of the string are returned.
Return Value
The Mid function returns a Variant (containing a String data type).
Related Functions
InStr | Left, Left$ | Right
Example
Dim strSource as String
Dim strFirstWord as String
Dim strSecondWord as String
Dim strThirdWord as String
Dim lngPosition as Long
Dim lngNextPosition as Long
Dim lngWordLength as Long
strSource = "Mid Function Demo" ' Create test string.
lngPosition = 1 ' Start at character position 1
lngNextPosition = Instr(lngPosition, strSource," ") ' Locate first space character
lngWordLength = lngNextPosition - lngPosition ' calculate word length
strFirstWord = Mid(strSource, lngPosition, lngWordLength) ' Returns first word "Mid"
lngPosition = lngNextPosition + 1 ' Move to next word position
lngNextPosition = Instr(lngPosition, strSource," ") ' Locate next space character
lngWordLength = lngNextPosition - lngPosition ' calculate word length
strSecondWord = Mid(strSource, lngPosition, lngWordLength) ' Returns second word "Function"
lngPosition = lngNextPosition + 1 ' Move to next word position
lngNextPosition = Instr(lngPosition, strSource," ") ' Locate next space character
lngWordLength = lngNextPosition - lngPosition ' calculate word length
strThirdWord = Mid(strSource, lngPosition, lngWordLength) ' Returns third word "Demo"