Sub 陳述式 (Visual Basic)Sub Statement (Visual Basic)

宣告定義 Sub 程式的名稱、參數和程式碼。Declares the name, parameters, and code that define a Sub procedure.

語法Syntax

[ <attributelist> ] [ Partial ] [ accessmodifier ] [ proceduremodifiers ] [ Shared ] [ Shadows ] [ Async ]
Sub name [ (Of typeparamlist) ] [ (parameterlist) ] [ Implements implementslist | Handles eventlist ]
    [ statements ]
    [ Exit Sub ]
    [ statements ]
End Sub

組件Parts

  • attributelist

    選擇性。Optional. 請參閱屬性清單See Attribute List.

  • Partial

    選擇性。Optional. 表示部分方法的定義。Indicates definition of a partial method. 請參閱部分方法See Partial Methods.

  • accessmodifier

    選擇性。Optional. 可以是下列其中一項:Can be one of the following:

    請參閱 Access levels in Visual BasicSee Access levels in Visual Basic.

  • proceduremodifiers

    選擇性。Optional. 可以是下列其中一項:Can be one of the following:

  • Shared

    選擇性。Optional. 請參閱共用See Shared.

  • Shadows

    選擇性。Optional. 請參閱ShadowsSee Shadows.

  • Async

    選擇性。Optional. 請參閱AsyncSee Async.

  • name

    必要。Required. 程式的名稱。Name of the procedure. 請參閱 Declared Element NamesSee Declared Element Names. 若要建立類別的函式程式,請將 Sub 程式的名稱設定為 New 關鍵字。To create a constructor procedure for a class, set the name of a Sub procedure to the New keyword. 如需詳細資訊,請參閱物件存留期:物件的建立和終結方式For more information, see Object Lifetime: How Objects Are Created and Destroyed.

  • typeparamlist

    選擇性。Optional. 泛型程式的類型參數清單。List of type parameters for a generic procedure. 請參閱類型清單See Type List.

  • parameterlist

    選擇性。Optional. 本機變數名稱的清單,代表此程式的參數。List of local variable names representing the parameters of this procedure. 請參閱參數清單See Parameter List.

  • Implements

    選擇性。Optional. 指出此程式會執行一或多個 Sub 程式,其中每一個都是在由這個程式的包含類別或結構所實的介面中定義。Indicates that this procedure implements one or more Sub procedures, each one defined in an interface implemented by this procedure's containing class or structure. 請參閱Implements 語句See Implements Statement.

  • implementslist

    如果使用 Implements,則為必要項。Required if Implements is supplied. 實作之 Sub 程序的清單。List of Sub procedures being implemented.

    implementedprocedure [ , implementedprocedure ... ]

    每個 implementedprocedure 都具有下列語法和組件:Each implementedprocedure has the following syntax and parts:

    interface.definedname

    組件Part 描述Description
    interface 必要。Required. 此程式的包含類別或結構所實作為介面的名稱。Name of an interface implemented by this procedure's containing class or structure.
    definedname 必要。Required. 名稱,據以在 interface 中定義程序。Name by which the procedure is defined in interface.
  • Handles

    選擇性。Optional. 指出此程式可以處理一或多個特定事件。Indicates that this procedure can handle one or more specific events. 請參閱控制碼See Handles.

  • eventlist

    如果使用 Handles,則為必要項。Required if Handles is supplied. 此程式處理的事件清單。List of events this procedure handles.

    eventspecifier [ , eventspecifier ... ]

    每個 eventspecifier 都具有下列語法和組件:Each eventspecifier has the following syntax and parts:

    eventvariable.event

    組件Part 描述Description
    eventvariable 必要。Required. 以引發事件之類別或結構的資料類型宣告的物件變數。Object variable declared with the data type of the class or structure that raises the event.
    event 必要。Required. 這個程式處理的事件名稱。Name of the event this procedure handles.
  • statements

    選擇性。Optional. 要在此程式內執行的語句區塊。Block of statements to run within this procedure.

  • End Sub

    終止這個程式的定義。Terminates the definition of this procedure.

備註Remarks

所有可執行檔程式碼都必須在程式內。All executable code must be inside a procedure. 當您不想要將值傳回給呼叫程式碼時,請使用 Sub 程式。Use a Sub procedure when you don't want to return a value to the calling code. 當您想要傳回值時,請使用 Function 程式。Use a Function procedure when you want to return a value.

定義 Sub 程式Defining a Sub Procedure

您只能在模組層級定義 Sub 程式。You can define a Sub procedure only at the module level. Sub 程式的宣告內容必須是類別、結構、模組或介面,而且不能是原始程式檔、命名空間、程式或區塊。The declaration context for a sub procedure must, therefore, be a class, a structure, a module, or an interface and can't be a source file, a namespace, a procedure, or a block. 如需詳細資訊,請參閱宣告內容和預設存取層級For more information, see Declaration Contexts and Default Access Levels.

Sub 程式預設為公開存取。Sub procedures default to public access. 您可以使用存取修飾詞來調整其存取層級。You can adjust their access levels by using the access modifiers.

如果程式使用 Implements 關鍵字,則包含的類別或結構必須具有緊接在其 ClassStructure 語句後面的 Implements 語句。If the procedure uses the Implements keyword, the containing class or structure must have an Implements statement that immediately follows its Class or Structure statement. Implements 語句必須包含 implementslist中指定的每個介面。The Implements statement must include each interface that's specified in implementslist. 不過,介面用來定義 Sub (在 definedname中)的名稱不一定要符合此程式的名稱(在 name中)。However, the name by which an interface defines the Sub (in definedname) doesn't have to match the name of this procedure (in name).

從 Sub 程式傳回Returning from a Sub Procedure

Sub 程式傳回呼叫程式碼時,會在呼叫它的語句後面繼續執行語句。When a Sub procedure returns to the calling code, execution continues with the statement after the statement that called it.

下列範例顯示從 Sub 程式傳回的。The following example shows a return from a Sub procedure.

Sub mySub(ByVal q As String)
    Return
End Sub

Exit SubReturn 語句會導致立即離開 Sub 程式。The Exit Sub and Return statements cause an immediate exit from a Sub procedure. 任何數目的 Exit SubReturn 語句都可以出現在程式中的任何位置,而且您可以混合 Exit SubReturn 語句。Any number of Exit Sub and Return statements can appear anywhere in the procedure, and you can mix Exit Sub and Return statements.

呼叫 Sub 程式Calling a Sub Procedure

您可以使用語句中的程式名稱來呼叫 Sub 程式,然後在該名稱後面加上括弧中的引數清單。You call a Sub procedure by using the procedure name in a statement and then following that name with its argument list in parentheses. 只有在未提供任何引數時,才可以省略括弧。You can omit the parentheses only if you don't supply any arguments. 不過,如果您一律包含括弧,則程式碼會更容易閱讀。However, your code is more readable if you always include the parentheses.

Sub 程式和 Function 程式都可以有參數,並執行一連串的語句。A Sub procedure and a Function procedure can have parameters and perform a series of statements. 不過,Function 程式會傳回值,而 Sub 程式則不會。However, a Function procedure returns a value, and a Sub procedure doesn't. 因此,您不能在運算式中使用 Sub 程式。Therefore, you can't use a Sub procedure in an expression.

當您呼叫 Sub 程式時,可以使用 Call 關鍵字,但不建議在大部分的情況下使用該關鍵字。You can use the Call keyword when you call a Sub procedure, but that keyword isn't recommended for most uses. 如需詳細資訊,請參閱Call 語句For more information, see Call Statement.

Visual Basic 有時會重新排列算術運算式,以提高內部效率。Visual Basic sometimes rearranges arithmetic expressions to increase internal efficiency. 基於這個理由,如果您的引數清單包含呼叫其他程式的運算式,您就不應該假設這些運算式會以特定順序呼叫。For that reason, if your argument list includes expressions that call other procedures, you shouldn't assume that those expressions will be called in a particular order.

非同步 Sub 程式Async Sub Procedures

藉由使用非同步功能,您可以叫用非同步函式,而不需使用明確回呼,或手動將程式碼分割成多個函數或 lambda 運算式。By using the Async feature, you can invoke asynchronous functions without using explicit callbacks or manually splitting your code across multiple functions or lambda expressions.

如果您使用Async修飾詞來標記程式,您可以在程式中使用Await運算子。If you mark a procedure with the Async modifier, you can use the Await operator in the procedure. 當控制項到達 Async 程式中的 Await 運算式時,控制項會回到呼叫端,而程式中的進度會暫停,直到等候的工作完成為止。When control reaches an Await expression in the Async procedure, control returns to the caller, and progress in the procedure is suspended until the awaited task completes. 當工作完成時,可以在程式中繼續執行。When the task is complete, execution can resume in the procedure.

注意

當遇到第一個尚未完成的等候物件或到達 Async 程式的結尾(以先發生者為准)時,Async 程式會傳回呼叫端。An Async procedure returns to the caller when either the first awaited object that’s not yet complete is encountered or the end of the Async procedure is reached, whichever occurs first.

您也可以使用 Async 修飾詞來標記函數語句You can also mark a Function Statement with the Async modifier. Async 函式的傳回型別可以是 Task<TResult>TaskAn Async function can have a return type of Task<TResult> or Task. 本主題稍後的範例會顯示具有 Task<TResult>傳回類型的 Async 函式。An example later in this topic shows an Async function that has a return type of Task<TResult>.

Async Sub 程式主要用於事件處理常式,因此無法傳回值。Async Sub procedures are primarily used for event handlers, where a value can't be returned. 無法等候 Async Sub 程式,Async Sub 程式的呼叫端無法攔截 Sub 程式擲回的例外狀況。An Async Sub procedure can't be awaited, and the caller of an Async Sub procedure can't catch exceptions that the Sub procedure throws.

Async 程式無法宣告任何ByRef參數。An Async procedure can't declare any ByRef parameters.

如需 Async 程式的詳細資訊,請參閱使用 async 和 Await 進行非同步程式設計非同步程式中的控制流程非同步傳回類型For more information about Async procedures, see Asynchronous Programming with Async and Await, Control Flow in Async Programs, and Async Return Types.

範例Example

下列範例會使用 Sub 語句來定義構成 Sub 程式主體的名稱、參數和代碼。The following example uses the Sub statement to define the name, parameters, and code that form the body of a Sub procedure.

Sub ComputeArea(ByVal length As Double, ByVal width As Double)
    ' Declare local variable.
    Dim area As Double
    If length = 0 Or width = 0 Then
        ' If either argument = 0 then exit Sub immediately.
        Exit Sub
    End If
    ' Calculate area of rectangle.
    area = length * width
    ' Print area to Immediate window.
    Debug.WriteLine(area)
End Sub

範例Example

在下列範例中,DelayAsync 是具有 Task<TResult>傳回類型的 Async FunctionIn the following example, DelayAsync is an Async Function that has a return type of Task<TResult>. DelayAsync 具有傳回整數的 Return 陳述式。DelayAsync has a Return statement that returns an integer. 因此,DelayAsync 的函式宣告必須具有 Task(Of Integer)的傳回類型。Therefore, the function declaration of DelayAsync must have a return type of Task(Of Integer). 因為傳回型別是 Task(Of Integer),所以 DoSomethingAsyncAwait 運算式的評估會產生整數,如下列語句所示: Dim result As Integer = Await delayTaskBecause the return type is Task(Of Integer), the evaluation of the Await expression in DoSomethingAsync produces an integer, as the following statement shows: Dim result As Integer = Await delayTask.

startButton_Click 的程式是 Async Sub 程式的範例。The startButton_Click procedure is an example of an Async Sub procedure. 因為 DoSomethingAsyncAsync 函式,所以必須等候 DoSomethingAsync 呼叫的工作,如下列語句所示: Await DoSomethingAsync()Because DoSomethingAsync is an Async function, the task for the call to DoSomethingAsync must be awaited, as the following statement shows: Await DoSomethingAsync(). startButton_Click Sub 程式必須使用 Async 修飾詞加以定義,因為它有 Await 運算式。The startButton_Click Sub procedure must be defined with the Async modifier because it has an Await expression.

' Imports System.Diagnostics
' Imports System.Threading.Tasks

' This Click event is marked with the Async modifier.
Private Async Sub startButton_Click(sender As Object, e As RoutedEventArgs) Handles startButton.Click
    Await DoSomethingAsync()
End Sub

Private Async Function DoSomethingAsync() As Task
    Dim delayTask As Task(Of Integer) = DelayAsync()
    Dim result As Integer = Await delayTask

    ' The previous two statements may be combined into
    ' the following statement.
    ' Dim result As Integer = Await DelayAsync()

    Debug.WriteLine("Result: " & result)
End Function

Private Async Function DelayAsync() As Task(Of Integer)
    Await Task.Delay(100)
    Return 5
End Function

'  Output:
'   Result: 5

請參閱See also