向过程中传递数据和从过程中获取数据

每条数据都通过参数传递到过程中。参数充当要传递到过程中的数据的占位符。您可以为参数指定任何有效的变量名称。使用 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()