编写 Function 过程Writing a Function procedure

Function 过程是由Function和**End function** 语句括起来的一系列 Visual Basic语句A Function procedure is a series of Visual Basic statements enclosed by the Function and End Function statements. Function过程与**Sub** 过程类似, 但函数还可以返回值。A Function procedure is similar to a Sub procedure, but a function can also return a value.

Function 过程可接受通过调用过程传递给它的参数(如常量变量表达式)。A Function procedure can take arguments, such as constants, variables, or expressions that are passed to it by a calling procedure. 如果 Function 过程没有参数,则其 Function 语句必须包括一对空括号。If a Function procedure has no arguments, its Function statement must include an empty set of parentheses. 函数通过在过程的一条或多条语句中将值分配给其名称来返回值。A function returns a value by assigning a value to its name in one or more statements of the procedure.

在以下示例中, Celsius 函数通过华氏度计算摄氏度。In the following example, the Celsius function calculates degrees Celsius from degrees Fahrenheit. 在从 Main 过程调用该函数时,将一个包含参数值的变量传递到该函数。When the function is called from the Main procedure, a variable containing the argument value is passed to the function. 计算结果会返回到调用过程并在消息框中显示。The result of the calculation is returned to the calling procedure and displayed in a message box.

Sub Main() 
 temp = Application.InputBox(Prompt:= _ 
 "Please enter the temperature in degrees F.", Type:=1) 
 MsgBox "The temperature is " & Celsius(temp) & " degrees C." 
End Sub 
 
Function Celsius(fDegrees) 
 Celsius = (fDegrees - 32) * 5 / 9 
End Function

另请参阅See also

支持和反馈Support and feedback

有关于 Office VBA 或本文档的疑问或反馈?Have questions or feedback about Office VBA or this documentation? 请参阅 Office VBA 支持和反馈,获取有关如何接收支持和提供反馈的指南。Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.