Functionプロシージャは、Function文とEnd Function文で囲まれた一連のBSL文です。FunctionプロシージャはSubプロシージャと似ていますが、値を戻すこともできます。Functionプロシージャは、引数(呼出し側プロシージャによって渡される定数、変数または式)を使用できます。Functionプロシージャに引数がない場合は、そのFunction文に一対の空のカッコを指定する必要があります。Functionは、プロシージャの1つ以上の文でFunctionの名前に値を割り当てることで値を戻します。Functionの戻り型は常にバリアントです。
次の例では、Celsius関数で華氏度から摂氏度を計算します。ConvertTemp Subプロシージャから関数がコールされると、引数値を含む変数が関数に渡されます。計算の結果が呼出し側プロシージャに戻され、メッセージ・ボックスに表示されます。
次の例は、Functionプロシージャの使用方法を示しています:
例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()