Skip to main content

Mid function

Table of contents
  1. Syntax
  2. Remarks
  3. Example

Returns a Variant (String) containing a specified number of characters from a string.

Syntax

Mid(string, start, [ length ])

The Mid function syntax has these named arguments:

Part Description
string Required. String expression from which characters are returned. If string contains Null, Null is returned.
start Required; Long. Character position in string at which the part to be taken begins. If start is greater than the number of characters in string, Mid returns a zero-length string ("").
length Optional; Variant (Long). Number of characters to return. If omitted or if there are fewer than length characters in the text (including the character at start), all characters from the start position to the end of the string are returned.

Remarks

To determine the number of characters in string, use the Len function.

Example

The first example uses the Mid function to return a specified number of characters from a string.

Dim MyString, FirstWord, LastWord, MidWords
MyString = "Mid Function Demo"    ' Create text string.
FirstWord = Mid(MyString, 1, 3)    ' Returns "Mid".
LastWord = Mid(MyString, 14, 4)    ' Returns "Demo".
MidWords = Mid(MyString, 5)    ' Returns "Function Demo".

The second example use MidB and a user-defined function (MidMbcs) to also return characters from string. The difference here is that the input string is ANSI and the length is in bytes.

Function MidMbcs(ByVal str As String, start, length)
    MidMbcs = StrConv(MidB(StrConv(str, vbFromUnicode), start, length), vbUnicode)
End Function

Dim MyString
MyString = "AbCdEfG"
' Where "A", "C", "E", and "G" are DBCS and "b", "d",
' and "f" are SBCS.
MyNewString = Mid(MyString, 3, 4)   ' Returns "CdEf"

MyNewString = MidB(MyString, 3, 4)  ' Returns "bC"

MyNewString = MidMbcs(MyString, 3, 4)   ' Returns "bCd"

Leave a comment

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

Format your code: <pre><code class="language-vba">place your code here</code></pre>