Passing Arguments by Value


You can also use the ByVal or ByRef keyword to define how parameters are passed to your procedure:

 Function MyFunction (ByVal Target as String) 

The ByVal keyword 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 variable x will be modified by what is going on within the function Adjust . 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 only affects the copy and not the variable itself. The variable x will 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. To avoid these effects, use the declaration ByVal .




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