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 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 return a value; if it performs a calculation, there is no direct way of finding the result. 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 use 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 by using a variable, as discussed in Chapter 2, to accept the return value:

 x=Now() 

The variable x will contain the value of today's date. This is a very simple example 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 functions can have parameters or values passed to them. These are passed inside parentheses (more on this in the next section).




Excel VBA Macro Programming
Excel VBA Macro Programming
ISBN: 0072231440
EAN: 2147483647
Year: 2004
Pages: 141

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net