FUNCTION PROCEDURES

A Function procedure is similar to a Sub procedure in that it can also take arguments and execute a series of statements. It differs from a Sub procedure in that (a) it is invoked through its name, and (b) it returns a single value.

A simplified representation of the syntax for Function procedures is:

Function FunctionProcedureName ([argumentList])
[statements]
[FunctionProcedureName = expression]
[Exit Function]
[statements]
[FunctionProcedureName = expression]
End Function

FunctionProcedureName is the name you give to the Function procedure,

argumentList represents the argument list that is passed to the Function procedure when it is called (multiple arguments are separated by commas),

statements are a group of statements to be executed within the Function procedure,

Exit Function is a statement that provides an immediate exit from the procedure prior to its completion.

Notice that a value is assigned to the function name. This value is returned upon completion of the function. Any number of such assignment can appear anywhere within the function.

The Function procedure is invoked by using the function's name, followed by the argument list in parentheses.

Here is an example that uses a Function to add up two numbers:

Sub SimpleAddition()
    'assign values
    a = 15
    b = 28
    'compute the sum
    c = Add(a, b)
    MsgBox c
End Sub

Function Add(a, b)
    Add = a + b
End Function

Because a Function returns a single value, it can be invoked outside of expressions.

For example, the preceding addition example can also be written as:

Sub SimpleAddition()
    'assign values
    a = 15
    b = 28
    'compute the sum
    MsgBox Add(a, b)
End Sub

Function Add(a, b)
    Add = a + b
End Function

In this case, Add is invoked as part of the message box.

Here is another example:

Sub ShowSum()
    MsgBox sumNo(3,5)
End Sub

Function sumNo(x, y)
    sumNo = x + y
End Function

The ShowSum sub procedure calls the sumNo function and returns an "8" in a message box.