共用方式為


Mid Function (Visual Basic) 

Returns a string containing a specified number of characters from a string.

Public Shared Function Mid( _
   ByVal str As String, _
   ByVal Start As Integer, _
   Optional ByVal Length As Integer _
) As String

Parameters

  • str
    Required. String expression from which characters are returned.
  • Start
    Required. Integer expression. Starting position of the characters to return. If Start is greater than the number of characters in str, the Mid function returns a zero-length string (""). Start is one based.
  • Length
    Optional. Integer expression. Number of characters to return. If omitted or if there are fewer than Length characters in the text (including the character at position Start), all characters from the start position to the end of the string are returned.

Exceptions

Exception type Error number Condition

ArgumentException

5

Start <= 0 or Length < 0.

See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You can compare the error number against the Number Property (Err Object).) However, when possible, you should consider replacing such error control with Structured Exception Handling Overview for Visual Basic.

Remarks

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

Visual Basic has a Mid function and a Mid statement. These elements both operate on a specified number of characters in a string, but the Mid function returns the characters while the Mid statement replaces the characters. For more information, see Mid Statement.

Note

The MidB function in previous versions of Visual Basic returns a string in bytes rather than characters. It is used primarily for converting strings in double-byte character set (DBCS) applications. All Visual Basic strings are in Unicode, and MidB is no longer supported.

Example

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

' Creates text string.
Dim TestString As String = "Mid Function Demo"
' Returns "Mid".
Dim FirstWord As String = Mid(TestString, 1, 3)
' Returns "Demo".
Dim LastWord As String = Mid(TestString, 14, 4)
' Returns "Function Demo".
Dim MidWords As String = Mid(TestString, 5)

Requirements

Namespace: Microsoft.VisualBasic

Module: Strings

Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)

See Also

Reference

String Manipulation Summary
Left Function (Visual Basic)
Len Function (Visual Basic)
Trim, LTrim, and RTrim Functions
Mid Statement
Right Function (Visual Basic)
ArgumentException

Concepts

Programming Element Support Changes Summary

Other Resources

Strings in Visual Basic
Introduction to Strings in Visual Basic