函式程序 (Visual Basic)

Function 程序是 FunctionEnd Function 陳述式所括住的一連串 Visual Basic 陳述式。 Function 程序會執行工作,然後將控制項傳回呼叫程式碼。 傳回控制項時,也會將值傳回給呼叫程式碼。

每次呼叫程序時,其陳述式都會執行,從 Function 陳述式之後的第一個可執行陳述式開始,並以出現的第一個 End FunctionExit FunctionReturn 陳述式結尾。

您可以在模組、類別或結構中定義 Function 程序。 預設為 Public,這表示您可以從應用程式中任何可存取您所定義模組、類別或結構的任何位置呼叫它。

Function 程序可接受引數,例如常數、變數或運算式,這些引數會透過呼叫程式碼傳遞給程序。

宣告語法

宣告 Function 程序的語法如下:

[Modifiers] Function FunctionName [(ParameterList)] As ReturnType
    [Statements]
End Function

修飾元可指定有關多載、覆寫、共用和遮蔽的存取層級和資訊。 如需詳細資訊,請參閱函式陳述式

您宣告每個參數的方式與子程序相同。

資料類型

每個 Function 程序都有一個資料型別,就像每個變數一樣。 這個資料型別是由 Function 陳述式中的 As 子句指定,它會決定函式傳回給呼叫程式碼的值之資料型別。 下列範例宣告說明這一點。

Function Yesterday() As Date
End Function

Function FindSqrt(radicand As Single) As Single
End Function

如需詳細資訊,請參閱函式陳述式中的「組件」。

傳回值

Function 程序傳回給呼叫程式碼的值稱為其傳回值。 程序會以下列兩種方式之一傳回此值:

  • 使用 Return 陳述式來指定傳回值,並立即將控制項傳回呼叫程式。 說明如下例。

    Function FunctionName [(ParameterList)] As ReturnType
        ' The following statement immediately transfers control back
        ' to the calling code and returns the value of Expression.
        Return Expression
    End Function
    
  • 在程序的一或多個陳述式中,將值指派給自己的函式名稱。 在 Exit FunctionEnd Function 陳述式執行之前,控制項不會傳回給呼叫程式。 說明如下例。

    Function FunctionName [(ParameterList)] As ReturnType
        ' The following statement does not transfer control back to the calling code.
        FunctionName = Expression
        ' When control returns to the calling code, Expression is the return value.
    End Function
    

將傳回值指派給函式名稱的優點是,控制項在遇到 Exit FunctionEnd Function 陳述式之前,不會從程序傳回。 這可讓您指派初步值,之後再視需要加以調整。

如需傳回值的詳細資訊,請參閱函式陳述式。 如需傳回陣列的相關資訊,請參閱陣列

呼叫語法

您可以在指派陳述式右側或運算式包含程序名稱與引數,然後叫用 Function 程序。 您必須為所有非選擇性的引數提供值,而且須以括弧括住引數清單。 如果未提供任何引數,您可以選擇省略括弧。

Function 程序的呼叫語法如下。

lvalue=functionname[(argumentlist)]

If ((functionname[(argumentlist)] / 3) <=expression) Then

呼叫 Function 程序時,不需要使用其傳回值。 如果沒有使用,則會執行函式的所有動作,但會忽略傳回值。 通常是用這種方式呼叫 MsgBox

宣告和呼叫的圖例

下列 Function 程序會根據其他兩邊的值,計算直角三角形的最長邊或斜邊。

Function Hypotenuse(side1 As Double, side2 As Double) As Double
    Return Math.Sqrt((side1 ^ 2) + (side2 ^ 2))
End Function

下列範例會顯示對 hypotenuse 的一般呼叫。

Dim testLength, testHypotenuse As Double
testHypotenuse = Hypotenuse(testLength, 10.7)

另請參閱