Procedimentos Function

O procedimento Function é uma série de instruções BSL englobadas pelas instruções Function e End Function. O procedimento Function é semelhante a um procedimento Sub, mas também pode retornar um valor. O procedimento Function pode receber argumentos (constantes, variáveis ou expressões que são transmitidas a ele por um procedimento de chamada). Se um procedimento Function não tiver argumentos, sua instrução Function deverá incluir um conjunto vazio de parênteses. O procedimento Function retorna um valor por meio da atribuição de um valor ao seu nome em uma ou mais instruções do procedimento. O tipo de retorno de um procedimento Function é sempre uma Variante.

No exemplo a seguir, a função Celsius calcula graus Celsius a partir de graus Fahrenheit. Quando a função é chamada no procedimento Sub ConvertTemp, uma variável com o valor do argumento é transmitida para a função. O resultado do cálculo é retornado para o procedimento de chamada e exibido em uma caixa de mensagem.

O exemplo a seguir ilustra o uso dos procedimentos Function:

Exemplo 1:

Function Celsius(fDegrees)
           Celsius = (fDegrees - 32) * 5 / 9
        End Function
        valCelcius = Celsius(90)

Exemplo 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()

Exemplo 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()