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 an End Sub statement.
In the Sub statement, follow the Sub keyword with the name of the procedure, then the parameter list in parentheses.
Place the procedure's code statements between the Sub and End Sub statements.
To create a procedure that returns a value
Outside any other procedure, use a Function statement, followed by an End Function statement.
In the Function statement, follow the Function keyword with the name of the procedure, then the parameter list in parentheses, and then an As clause specifying the data type of the return value.
Place the procedure's code statements between the Function and End 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 or Function 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.
The following Function procedure calculates the longest side, or hypotenuse, of a right triangle, given the values for the other two sides.
Function hypotenuse(ByVal side1 As Single, ByVal side2 As Single) As Single Return Math.Sqrt((side1 ^ 2) + (side2 ^ 2)) End Function