함수 프로시저는 Function 및 End Function 명령문으로 둘러싸인 일련의 BSL 명령문입니다. Function 프로시저는 Sub 프로시저와 유사하지만, 값을 반환할 수도 있습니다. Function 프로시저는 인수(호출 프로시저에 의해 전달되는 상수, 변수 또는 표현식)를 받을 수 있습니다. Function 프로시저에 인수가 없는 경우 해당 Function 명령문에는 빈 괄호 세트가 포함되어야 합니다. Function은 1개 이상의 프로시저 명령문에서 이름에 값을 지정하여 값을 반환합니다. Function의 반환 유형은 항상 Variant입니다.
다음 예에서 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()