Access VBA Macro Programming

(Joao Candeias) #1
TheByValkeyword ensures that parameters are passed by value rather than by a reference to
a value from a variable. Passing a value by reference can easily allow bugs to creep into your
code. To demonstrate this, if you pass by reference using a variable name, the value of that
variable can be changed by the procedure that the variable is passed to—for example,

x = 100
z = Adjust(x)
Function Adjust(ByRef Target as Integer)

The variablexwill be modified by what is going on within the functionAdjust. However, if
you pass by value, as shown here, only a copy of the variable is passed to the procedure:

x = 100
z = Adjust(x)
Function Adjust(ByVal Target as Integer)

If the procedure changes this value, the change affects only the copy, not the variable itself.
The variablexwill always keep its value of 100.
Normally, you would not expect a function to modify an argument, but it can happen and
can lead to hard-to-find bugs within the code. Sometimes you do require the function to
modify the value of a variable, which is when it would be appropriate to use ByRef, but
generally ByValue is used the most.

34 Microsoft Access 2010 VBA Macro Programming

Free download pdf