Function 程序是以 Function 和 End Function 陳述式括住的一系列 BSL 陳述式。Function 程序與 Sub 程序類似,但也可以傳回值。Function 程序可以採用引數 (常數、變數或由呼叫程序傳遞給它的表示式)。如果 Function 程序沒有引數,則其 Function 陳述式必須包含一組空的括號。Function 會透過在程序的一或多個陳述式中為其名稱指派值來傳回值。傳回的 Function 類型一律為「變異」。
在下列範例中,Celsius 函式會根據華氏度數計算攝氏度數。從 ConvertTemp Sub 程序呼叫函式時,會將包含引數值的變數傳遞至此函式。計算的結果會傳回呼叫程序,並顯示在訊息方塊中。
下列範例說明函式程序的用法:
範例 1:
Function Celsius(fDegrees)
Celsius = (fDegrees - 32) * 5 / 9
End Function
valCelcius = Celsius(90)
範例 2:
Function AddNumbers(a, b)
AddNumbers = a + b ' The function returns the sum of a and b.
End Function
Sub ShowAddition()
Dim result
result = AddNumbers(5, 10) ' Calls the function and stores the result.
'Here result is 15
End Sub
Call ShowAddition()
範例 3:
Function CalculateRectangleArea(length, width)
If length <= 0 Or width <= 0 Then
CalculateRectangleArea = "Invalid dimensions" ' Returns an error message for invalid dimensions.
Else
CalculateRectangleArea = length * width ' Returns the area of the rectangle.
End If
End Function
Sub ShowRectangleArea()
Dim length, width, area
length = 4
width = 3
area = CalculateRectangleArea(length, width) ' Calls the function and stores the result.
'The area of the rectangle is 12
End Sub
Call ShowRectangleArea()