Inserimento ed estrazione di dati nelle routine

Ogni dato viene trasmesso alle routine utilizzando un argomento. Gli argomenti fungono da segnaposto per i dati che si desidera passare alla routine. Agli argomenti è possibile assegnare un qualsiasi nome di variabile valido. Quando si crea una routine utilizzando l'istruzione Sub o Function, le parentesi devono essere inserite dopo il nome della procedura. Tutti gli argomenti vengono racchiusi tra parentesi e separati da virgole. Nell'esempio seguente, fDegrees è un segnaposto per il valore passato alla funzione Celsius per la conversione.

Nell'esempio seguente viene illustrato l'uso del recupero dei dati da una routine.

Esempio 1

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

Per recuperare dati da una routine, è necessario utilizzare una routine Function. Tenere presente che una routine Function può restituire un valore. Una subroutine, invece, non restituisce valori.

Esempio 2

Function Celsius(fDegrees)
        Celsius = (fDegrees - 32) * 5 / 9   ' Converts Fahrenheit to Celsius.
End Function

Sub ConvertTemp()
        Dim temp, celsiusTemp
        temp = 70
        celsiusTemp = Celsius(temp)   ' Calls the function and stores the result.
'celsiusTemp has the converted temperature.
End Sub
Call ConvertTemp()

Esempio 3

Function Add(a, b)
    Add = a + b    ' Returns the sum of a and b.
End Function

Sub ShowAddition()
    Dim result
    result = Add(5, 10)    ' Calls the function and stores the result.
    'Here result is 15
End Sub
Call ShowAddition()

Esempio 4

Function GetGreeting(name, timeOfDay)
    If timeOfDay = "Morning" Then
        GetGreeting = "Good morning, " & name & "!"
    ElseIf timeOfDay = "Afternoon" Then
        GetGreeting = "Good afternoon, " & name & "!"
    ElseIf timeOfDay = "Evening" Then
        GetGreeting = "Good evening, " & name & "!"
    Else
        GetGreeting = "Hello, " & name & "!"
    End If
End Function

Sub ShowGreeting()
    Dim name, timeOfDay, greeting
    name = "MyName"
    timeOfDay = "Morning"
    greeting = GetGreeting(name, timeOfDay)   
    'Print greeting here
End Sub
Call ShowGreeting()