Writing a Function procedure

A Function procedure is a series of Visual Basic statements enclosed by the Function and End Function statements. A Function procedure is similar to a Sub procedure, but a function can also return a value.

A Function procedure can take arguments, such as constants, variables, or expressions that are passed to it by a calling procedure. 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.

In the following example, the Celsius function calculates degrees Celsius from degrees Fahrenheit. 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

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.