Function 过程是由 Function 和 End Function 语句括起来的一系列 BSL 语句。Function 过程与 Sub 过程类似,但还可以返回值。Function 过程可以接受参数(调用过程传递给它的常量、变量或表达式)。如果 Function 过程没有参数,则其 Function 语句必须包含一组空的括号。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()