Subroutines
- Last UpdatedJul 18, 2023
- 2 minute read
A VBA subroutine starts with the SUB statement and finishes with the END SUB statement. All other statements that lie between the SUB and END SUB statements, will be executed by the subroutine, when called to do so.
In the following subroutine syntax example:
-
Every placeholder shown inside arrow brackets ( <placeholder>) should be replaced in any actual code with the value of the item that it describes. The arrow brackets and the word they contain should not be included in the statement, and are shown here only for your information.
-
Statements shown between square brackets ( [ ]) are optional. The square brackets should not be included in the statement, and are shown here only for your information.
In VBA, Subroutines are created with the SUB statement in the following format.
Sub <SubName> ( [ Byval ] [ <Argument/s> ] [ <As Data Type> ])
<statement>
<statement>
<statement>
End Sub
Where:
-
[Byval] is the optional parameter for the argument;
-
Sub is the required subroutine statement basic keyword
-
<SubName> represents the required name of the subroutine being created
-
<Argument/s> represents the optional argument/s of the subroutine
-
<statement> represents the executable VBA script statement/s
-
End Sub is the subroutine terminating statement
The name given to the subroutine immediately follows the SUB keyword, and is used to identify the subroutine to VBA. This name is referred to when the subroutine is called upon (called) to be executed (perform the statements it contains) by some other procedure in VBA.
Subroutine names can contain the letters 'A' to 'Z' and 'a' to 'z', the underscore '_' and digits '0' to '9'. The subroutine name must begin with a letter, be no longer than 40 characters, cannot contain the space character, and cannot be a reserved word. Subroutine names (once declared), become a keyword in VBA. Like most keywords in VBA, these names are not case sensitive.
The subroutine name always ends with a pair of parentheses ( ) which may or may not contain one or more arguments required by (necessary for use in) the subroutine . Multiple arguments if used, are separated by commas ( , ). See Arguments for more details and argument syntax.
All the lines located between the SUB and the END SUB statements, contain the statements that will be executed when the subroutine is called in VBA. These statements will be executed one at a time in logical order from top to bottom within the subroutine.