每一筆資料都是透過引數傳入程序。引數可作為您要傳入程序之資料的預留位置。您可以將引數命名為任何有效的變數名稱。當您使用 Sub 陳述式或 Function 陳述式建立程序時,必須在程序名稱之後加上括號。所有引數都需置於括號內,並以逗號分隔。例如,在下列範例中,fDegrees 是傳入 Celsius 函式進行轉換之值的預留位置。
下列範例說明將資料輸出程序的用法:
範例 1:
Function Celsius(fDegrees) Celsius = (fDegrees - 32) * 5 / 9 End Function
若要將資料輸出程序,您必須使用 Function。請注意,Function 程序可傳回值;Sub 程序則無法傳回值。
範例 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()
範例 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()
範例 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()