Function Statement
Description
Declares the name, arguments, and code that form the body of a Function procedure.
Syntax
[Public | Private] [Static] Function name [(arglist)] [As type]
[statements]
[name = expression]
[Exit Function]
[statements]
[name = expression]
End Function
The Function statement syntax has these parts:
Part | Description |
|
Public | Optional. Indicates that the Function procedure is accessible to all other procedures in all modules. If used in a module that contains an Option Private, the procedure is not available outside the project. |
Private | Optional. Indicates that the Function procedure is accessible only to other procedures in the module where it is declared. |
Static | Optional. Indicates that the Function procedure's local variables are preserved between calls. The Static attribute doesn't affect variables that are declared outside the Function, even if they are used in the procedure. |
name | Required. Name of the Function; follows standard variable naming conventions. |
arglist | Optional. List of variables representing arguments that are passed to the Function procedure when it is called. Multiple variables are separated by commas. |
(continued)
type | Optional. Data type of the value returned by the Function procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (not currently supported), Date, String, or (except fixed length), Object, Variant, or any user-defined type. Arrays of any type can't be returned, but a Variant containing an array can. |
statements | Optional. Any group of statements to be executed within the Function procedure. |
expression | Optional. Return value of the Function. |
The arglist argument has the following syntax and parts:
[Optional] [ByVal | ByRef] [ParamArray] varname[( )] [As type] [= defaultvalue]
Part | Description |
|
Optional | Optional. Indicates that an argument is not required. If used, all subsequent arguments in arglist must also be optional and declared using the Optional keyword. Optional can't be used for any argument if ParamArray is used. |
ByVal | Optional. Indicates that the argument is passed by value. |
ByRef | Optional. Indicates that the argument is passed by reference. ByRef is the default in Visual Basic. |
ParamArray | Optional. Used only as the last argument in arglist to indicate that the final argument is an Optional array of Variant elements. The ParamArray keyword allows you to provide an arbitrary number of arguments. It may not be used with ByVal, ByRef, or Optional. |
varname | Required. Name of the variable representing the argument; follows standard variable naming conventions. |
type | Optional. Data type of the argument passed to the procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Decimal (not currently supported) Date, String (variable length only), Object, Variant. If the parameter is not Optional, a user-defined type or an object type may also be specified. |
defaultvalue | Optional. Any constant or constant expression. Valid for Optional parameters only. If the type is an Object, an explicit default value can only be Nothing. |
Remarks
If not explicitly specified using either Public or Private, Function procedures are public by default. If Static is not used, the value of local variables is not preserved between calls.
Caution Function procedures can be recursive; that is, they can call themselves to perform a given task. However, recursion can lead to stack overflow. The Static keyword is usually not used with recursive Function procedures.
All executable code must be in procedures. You can't define a Function procedure inside another Function, Sub, or Property procedure.
The Exit Function statement causes an immediate exit from a Function procedure. Program execution continues with the statement following the statement that called the Function procedure. Any number of Exit Function statements can appear anywhere in a Function procedure.
Like a Sub procedure, a Function procedure is a separate procedure that can take arguments, perform a series of statements, and change the values of its arguments. However, unlike a Sub procedure, you can use a Function procedure on the right side of an expression in the same way you use any intrinsic function, such as Sqr, Cos, or Chr, when you want to use the value returned by the function.
You call a Function procedure using the function name, followed by the argument list in parentheses, in an expression. See the Call statement for specific information on how to call Function procedures.
To return a value from a function, assign the value to the function name. Any number of such assignments can appear anywhere within the procedure. If no value is assigned to name, the procedure returns a default value: a numeric function returns 0, a string function returns a zero-length string (" "), and a Variant function returns Empty. A function that returns an object reference returns Nothing if no object reference is assigned to name (using Set) within the Function.
The following example shows how to assign a return value to a function named BinarySearch. In this case, False is assigned to the name to indicate that some value was not found.
Function BinarySearch(. . .) As Boolean
. . .
' Value not found. Return a value of False.
If lower > upper Then
BinarySearch = False
Exit Function
End If
. . .
End Function
Variables used in Function procedures fall into two categories: those that are explicitly declared within the procedure and those that are not. Variables that are explicitly declared in a procedure (using Dim or the equivalent) are always local to the procedure. Variables that are used but not explicitly declared in a procedure are also local unless they are explicitly declared at some higher level outside the procedure.
Caution A procedure can use a variable that is not explicitly declared in the procedure, but a naming conflict can occur if anything you defined at the module level has the same name. If your procedure refers to an undeclared variable that has the same name as another procedure, constant, or variable, it is assumed that your procedure refers to that module-level name. Explicitly declare variables to avoid this kind of conflict. You can use an Option Explicit statement to force explicit declaration of variables.
Caution Visual Basic may rearrange arithmetic expressions to increase internal efficiency. Avoid using a Function procedure in an arithmetic expression when the function changes the value of variables in the same expression.
See Also
Call statement, Dim statement, Option Explicit statement, Property Get statement, Property Let statement, Property Set statement, Sub statement.
Specifics (Microsoft Access)
In Microsoft Access, a public Function procedure is available to all other procedures in the current database and in referencing Microsoft Access databases. However, it is not available to any other applications.
If you declare a Function procedure as private in any module by preceding it with the Private keyword, that procedure is available only to other procedures in the same module.
If a Function procedure is declared as public within a private module, such as a class module, then the procedure is available to all other procedures in that database, but is not available to other Microsoft Access databases.
Example
This example uses the Function statement to declare the name, arguments, and code that form the body of a Function procedure. The last example uses hard-typed, initialized Optional arguments.
' The following user-defined function returns the square root of the
' argument passed to it.
Function CalculateSquareRoot(NumberArg As Double) As Double
If NumberArg < 0 Then ' Evaluate argument.
Exit Function ' Exit to calling procedure.
Else
CalculateSquareRoot = Sqr(NumberArg) ' Return square root.
End If
End Function
Using the ParamArray keyword enables a function to accept a variable number of arguments. In the following definition, FirstArg is passed by value.
Function CalcSum(ByVal FirstArg As Integer, ParamArray OtherArgs())
Dim ReturnValue
' If the function is invoked as follows:
ReturnValue = CalcSum(4, 3 ,2 ,1)
' Local variables are assigned the following values: FirstArg = 4,
' OtherArgs(1) = 3, OtherArgs(2) = 2, and so on, assuming default
' lowerbound for arrays = 1.
Optional arguments can now have default values and types other than Variant.
' If a function's arguments are defined as follows:
Function MyFunc(MyStr As String, Optional MyArg1 As _ Integer = 5, _
Optional MyArg2 = "Dolly")
Dim RetVal
' The function can be invoked as follows:
RetVal = MyFunc("Hello", 2, "World") ' All 3 arguments supplied.
RetVal = MyFunc("Test", , 5) ' Second argument omitted.
' Arguments one and three using named-arguments.
RetVal = MyFunc(MyStr:="Hello ", MyArg1:=7)