Mid 函数Mid function

返回一个 Variant (String),其中包含字符串中的指定数量的字符。Returns a Variant (String) containing a specified number of characters from a string.


Mid(string, start, [ length ])Mid(string, start, [ length ])

Mid 函数语法包含以下命名参数The Mid function syntax has these named arguments:

PartPart 说明Description
stringstring 必需。Required. 从中返回字符的字符串表达式String expression from which characters are returned. 如果_字符串_包含 Null,则返回 NullIf string contains Null, Null is returned.
startstart 必需,LongRequired; Long. _字符串_中被视为开始部分的字符位置。Character position in string at which the part to be taken begins. 如果 start 大于_字符串_中的字符数,则 Mid 返回零长度字符串 ("")。If start is greater than the number of characters in string, Mid returns a zero-length string ("").
Lengthlength 可选;Variant (Long)。Optional; Variant (Long). 要返回的字符的数目。Number of characters to return. 如果省略此部分或此部分中的数目少于文本中的 length 字符数(包括 start 处的字符),则将返回从 start 位置到字符串末尾的所有字符。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.


若要确定_字符串_中字符的数量,请使用 Len 函数。To determine the number of characters in string, use the Len function.


与在双字节字符集语言中一样,将 MidB 函数用于字符串中包含的字节数据。Use the MidB function with byte data contained in a string, as in double-byte character set languages. 参数将指定字节数,而不是指定字符数。Instead of specifying the number of characters, the arguments specify numbers of bytes. 有关使用 MidB 的示例代码,请参阅示例主题中的第二个示例。For sample code that uses MidB, see the second example in the example topic.


第一个示例使用 Mid 函数返回字符串中的指定数目的字符。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".

第二个示例使用 MidB 和用户定义的函数 (MidMbcs) 返回字符串中的字符。The second example use MidB and a user-defined function (MidMbcs) to also return characters from string. 此处的差别在于,输入字符串用 ANSI 表示,而长度用字节表示。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"

另请参阅See also

支持和反馈Support and feedback

有关于 Office VBA 或本文档的疑问或反馈?Have questions or feedback about Office VBA or this documentation? 请参阅 Office VBA 支持和反馈,获取有关如何接收支持和提供反馈的指南。Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.