Una routine Function è una serie di istruzioni BSL racchiuse dalle istruzioni Function e End Function. Una routine Function è simile a una subroutine, ma può anche restituire un valore. Una routine Function può includere argomenti (costanti, variabili o espressioni che vengono passate da una routine di chiamata). Se una routine Function non include argomenti, la relativa istruzione Function deve includere un set vuoto di parentesi. Una routine Function restituisce un valore assegnando un valore al relativo nome in una o più istruzioni della routine. Il tipo restituito da una funzione è sempre una variabile Variant.
Nell'esempio seguente, la funzione Celsius calcola i gradi Celsius in base ai gradi Fahrenheit. Quando la funzione viene richiamata dalla subroutine ConvertTemp, alla funzione viene passata una variabile contenente il valore dell'argomento. Il risultato del calcolo viene restituito alla routine di chiamata e visualizzato in una casella di messaggio.
Nell'esempio seguente viene illustrato l'uso delle routine Function.
Esempio 1
Function Celsius(fDegrees)
Celsius = (fDegrees - 32) * 5 / 9
End Function
valCelcius = Celsius(90)
Esempio 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()
Esempio 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()