All executable code must be inside a procedure. Use a Sub procedure when you do not need to return a value to the calling code. Use a Function procedure when you need to return a value.

You can use Sub only at module level. This means the declaration context for a sub procedure must be a class, structure, module, or interface, and cannot be a source file, namespace, procedure, or block. For more information, see Declaration Contexts and Default Access Levels.

Sub procedures default to public access. You can adjust their access levels with the access modifiers.

Rules

Implementation. If this procedure uses the Implements keyword, the containing class or structure must have an Implements statement immediately following its Class or Structure statement. The Implements statement must include each interface specified in implementslist. However, the name by which an interface defines the Sub (in definedname) does not have to be the same as the name of this procedure (in name).

Behavior

Returning from a Procedure. When the Sub procedure returns to the calling code, execution continues with the statement following the statement that called it.

The Exit Sub and Return statements cause an immediate exit from a Sub procedure. Any number of Exit Sub and Return statements can appear anywhere in the procedure, and you can mix Exit Sub and Return statements.

Calling a Procedure. A Sub procedure, like a Function procedure, is a separate procedure that can take parameters and perform a series of statements. However, unlike a Function procedure, which returns a value, a Sub procedure cannot be used in an expression.

You call a Sub procedure by using the procedure name, followed by the argument list in parentheses, in a statement. You can omit the parentheses only if you are not supplying any arguments. However, your code is more readable if you always include the parentheses.

You can optionally use the Call statement to call a Sub procedure. This can improve the readability of your code.

Troubleshooting

Order of Execution. Visual Basic sometimes rearranges arithmetic expressions to increase internal efficiency. For that reason, if your argument list includes expressions that call other procedures, you cannot rely on them being called in any particular order.