Chapter 10 Creating Modules and Procedures 257
a function in a program by placing the function name in a program statement along with any
required arguments.
Arguments are the data used to make functions work, and they must be included between
parentheses and be separated by commas. Basically, using a Function procedure is exactly
like using a built-in function or method such as Int, Rnd, or FromFile.
Tip Functions declared in modules are public by default. As a result, you can use them in any
event procedure within the project.
Function Syntax
The basic syntax of a function is as follows:
Function FunctionName([arguments]) As Type
function statements
[Return value]
End Function
The following syntax items are important:
n FunctionName is the name of the function you’re creating.
n As Type is a pair of keywords that specifies the function return type. It is strongly
recommended that you specify a specific data type. If you don’t provide a type, the
return type defaults to Object.
n arguments is a list of optional arguments (separated by commas) to be used in the
function. Each argument should also be declared as a specific type. (By default, Visual
Basic adds the ByVal keyword to each argument, indicating that a copy of the data is
passed to the function through this argument but that any changes to the arguments
won’t be returned to the calling routine .)
n function statements is a block of statements that accomplishes the work of the function.
The first statements in a function typically declare local variables that will be used in
the function, and the remaining statements perform the work of the function.
n Return allows you to return a value to the calling procedure and specify that value.
The type of the return value must be the same type as specified in the As Type
keywords. When a Return statement is executed, the function is exited, so if there
are any function statements after the Return statement, these won’t be executed.
(Alternatively, you can return a value to the calling routine by assigning the value to
FunctionName .)
n Brackets ( [] ) enclose optional syntax items. Visual Basic requires that those syntax
items are not enclosed by brackets.
Functions always return a value to the calling procedure in the function’s name
(FunctionName). For this reason, the last statement in a function is often an assignment