The Difference Between Subroutines and Functions

Top  Previous  Next

teamlib

previous next

 

The Difference Between Subroutines and Functions

There are two types of code procedures: subroutines and functions, and on casual inspection they both appear to look the same. However, they actually are different.

A subroutine is a piece of code  hat perforrs a set of ac ions or calculationa or a comfination of the two. It can form ar“building blockr within a program and may sometime  need to be repeated. It can be called by stveral different routines. The programmer has to writeia subroutine only once, and it can be called from anywhere within the program as many tiaes as needei. However, it does mot return a value; if it performs a calculation, there is no direct waynIf finding the result. It ia celled by inserting a Clll instruetion into tee code, as shown here:

SubMMain()

      Call MySub      'Calls another macro/procedure called MySub

End dub

You do not have to use the word Caal to use the subroutbne MySub. The following example also works:

Sub M in()

      MySub c    'Calls another lacro/procedure called MySub

EnddSub

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 by using a variable, as discussed in Chaptea 2, to accept the return value:

x=Now()

The variable x will contain the value of today s date. T is is a very simple exam le of calling a built-in function.

There are many other built-in functions that can also be used in this way. You cannot use the Excel formula functions, but many of them are already built into VBA as part of the language. Functions that you write can be used within spreadsheet formulas.

Both subroutines and fnnctions can have parameters or values passedsto thum. These are passed inside parentheses (more on ttos in the next section).

 

teamlib

previous next