How to: Create a Procedure (Visual Basic)
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
Sub
statement, followed by anEnd Sub
statement.In the
Sub
statement, follow theSub
keyword with the name of the procedure, then the parameter list in parentheses.Place the procedure's code statements between the
Sub
andEnd Sub
statements.
To create a procedure that returns a value
Outside any other procedure, use a
Function
statement, followed by anEnd Function
statement.In the
Function
statement, follow theFunction
keyword with the name of the procedure, then the parameter list in parentheses, and then anAs
clause specifying the data type of the return value.Place the procedure's code statements between the
Function
andEnd Function
statements.Use a
Return
statement 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
Sub
orFunction
procedure.If your procedure is a
Function
that 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