Access VBA Macro Programming

(Joao Candeias) #1

Afunctionis exactly like a subroutine except that it returns a value. Functions start with
Function(instead ofSub) and end withEnd Function(instead ofEnd Sub). This means
that, generally speaking, functions should be called using a variable, as discussed in Chapter 2,
to accept the return value:


x=Now()


The variablexwill 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).


Writing a Simple Subroutine


A subroutine is different from a function in that it does not return anything directly and so
cannot be used directly in the code the way a function can. A subroutine is usually a building
block that forms a piece of code that will be called many times, possibly from different points
within your program. This is one of the great flexibilities of a subroutine. When it is called,
the return address (from where the subroutine was called) is stored. When the subroutine
finishes running, control is passed back to the return address. You can still pass parameters to
it, but these are used internally within the code itself.
Click back to Module1 and add the following code:


Sub Display(Target)
MsgBox Target
End Sub


Note that this subroutine has an argument parameter for a variable calledtarget. This is
because you are going to call the subroutine from another procedure and pass a variable
across.
A line is drawn to differentiate the new subroutine, and the subroutine you have written is
automatically added to the drop-down in the top-left corner. Now return to the initial Hello
World example from Chapter 1 and add the following code:


Sub MyCode()
'MsgBox "Hello World"
x = 3 * 5
MsgBox x
Call Display("my subroutine")
End Sub


Make sure you have already defined the function called “Display,” otherwise you will get an
error when you try to run MyCode.
Click the mouse cursor anywhere on the MyCode procedure and then click the Run icon
on the VBE toolbar or pressF5. You will see the message box showing 15, followed by a
message box showing “my subroutine.”


Chapter 3: Modules, Functions, and Subroutines 29

Free download pdf