Difference Between Subroutines and Functions
Subroutines and functions are two types of code procedures. On casual inspection, they appear to be the same. In truth, however, they are different.
A subroutine is a piece of code that performs a set of actions or calculations, or a combination of the two. It can form a "building block" within a program and may sometimes need to be repeated. It can be called by several different routines. The programmer has to write a subroutine only once, and it can be called from anywhere within the program as many times as needed. However, it does not directly return a value; if it performs a calculation, there is no direct way of finding the result. It can alter values of variables if you pass parameters using the ByRef methodology, which is explained later in this tutorial. It is called by inserting a Call instruction into the code, as shown here:
Sub Main() Call MySub 'Calls another macro/procedure called MySub End Sub
You do not have to use the word Call to utilize the subroutine MySub. The following example also works:
Sub Main() MySub 'Calls another macro/procedure called MySub End Sub
A function is exactly like a subroutine except that it returns a value. Functions start with Function (instead of Sub) and end with End Function (instead of End Sub). This means that, generally speaking, functions should be called using a variable, to accept the return value:
The variable x will contain the value of today's date. This is a very simple example of calling a built-in function.
Both subroutines and functions can have parameters or values passed to them. These are passed inside parentheses (more on this in the next section).