Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
You enclose a procedure between a starting declaration statement (Sub or Function) and an ending declaration statement (End Sub or End Function). All the procedure's code lies between these statements.
A procedure cannot contain another procedure, so its starting and ending statements must be outside any other procedure.
If you have code that performs the same task in different places, you can write the task once as a procedure and then call it from different places in your code.
To create a procedure that does not return a value
Outside any other procedure, use a
Substatement, followed by anEnd Substatement.In the
Substatement, follow theSubkeyword with the name of the procedure, then the parameter list in parentheses.Place the procedure's code statements between the
SubandEnd Substatements.
To create a procedure that returns a value
Outside any other procedure, use a
Functionstatement, followed by anEnd Functionstatement.In the
Functionstatement, follow theFunctionkeyword with the name of the procedure, then the parameter list in parentheses, and then anAsclause specifying the data type of the return value.Place the procedure's code statements between the
FunctionandEnd Functionstatements.Use a
Returnstatement to return the value to the calling code.
To connect your new procedure with the old, repetitive blocks of code
Make sure you define the new procedure in a place where the old code has access to it.
In your old, repetitive code block, replace the statements that perform the repetitive task with a single statement that calls the
SuborFunctionprocedure.If your procedure is a
Functionthat returns a value, ensure that your calling statement performs an action with the returned value, such as storing it in a variable, or else the value will be lost.
Example
The following Function procedure calculates the longest side, or hypotenuse, of a right triangle, given the values for the other two sides:
Function Hypotenuse(side1 As Double, side2 As Double) As Double
Return Math.Sqrt((side1 ^ 2) + (side2 ^ 2))
End Function