Professional Documents
Culture Documents
This chapter shows how to use some of the more advanced programming techniques in VBA,
such as passing arguments by reference and value, using optional arguments and writing
recursive programs.
By default in VBA arguments are passed by reference (ByRef) rather than by value (ByVal).
What does this mean?
The example code below calculates the factorial of a number (eg 4! = 4 * 3 * 2 * 1 = 24).
Running the macro for an input of 4 should give the following dialog boxes:
Here is a macro to do this – it’s not particularly well written, but it shows the principles:
The following subroutine would achieve exactly the same results, but has been written to pass
arguments by value:
It is a source of lively debate in the Wise Owl office whether it is better to pass arguments by
reference or to use public variables. The following two routines both calculate the factorial of an
input number:
… as it will be visible in
the subroutine also.
♦ Purist programmers will argue that you should avoid public variables, as you can never
be certain that their value won’t be inadvertently changed by other routines – all
common values should be passed into subroutines by reference.
♦ Realists will argue that using public variables creates shorter code which is easier to
understand (there are less long lists of arguments to interpret).
One of the most powerful programming techniques is to write macros which call themselves.
A typical example of recursive programming is to list out all of the members of a tree. Consider
the following spreadsheet of employees:
To solve this problem we need to list out for each employee chosen:
And so on for as many levels as it takes! Experienced programmers will immediately recognise
that we can write one function to list out an employee’s immediate subordinates, and call this
recursively.
Optional arguments are a powerful technique – they allow you to make one routine do two
different things.
Suppose that we now add another argument to the Owner table stating whether an owner is a
celebrity or not:
We can solve our problem without having to rewrite every call to AddOwner by making the
argument optional:
The following code would call this routine twice – once setting the 3rd argument, once not:
Optional arguments must be the last ones in the list, which is why the
following subroutine declaration appears in red as invalid syntax:
Wise Owl’s
Hint
Dedicated programmers might like to look at an alternative way to pass arrays of optional
arguments, using ParamArray. To solve the problem below, you could use 3 optional
arguments:
The ParamArray keyword can only be used under the following circumstances:
♦ It must have data type Variant (even though in the above example we know we’ll be
passing strings of text).
♦ It must be the last argument in the list, just like for Optional arguments.