Previous Document Next Document

Understanding automation : How is automation coding structured? : Allocating memory


Allocating memory

VBA does not support C-style memory pointers. Memory allocation and garbage collection are automatic and transparent, just as in Java and JavaScript (and some C++ code).

Passing arguments

Most languages, including C++ and Java, pass an argument to a procedure as a copy of the original. If the original must be passed, then one of two things can happen:

 
a memory pointer is passed that directs the procedure to the original argument in memory
 
a reference to the original argument is passed

Microsoft Visual Basic (VB) has the same requirements for passing arguments. In VB, passing a copy of the original argument is called “passing by value” and passing a reference to the original is called “passing by reference.”

By default, function and subroutine parameters are passed by reference. A reference to the original variable is passed in the argument of the procedure; changing the value of that argument, in effect, changes the value of the original variable value as well. In this way, more than one value can be returned from a function or subroutine. To explicitly annotate the code to indicate that an argument is being passed by reference, you can prefix the argument with ByRef.

If you want to prevent a procedure from changing the value of the original variable, you can force the copying of an argument. To do this in VBA, prefix the argument with ByVal, as shown in the example that follows. The functionality of ByRef and ByVal is similar to the ability of C and C++ to pass a copy of a variable, or to pass a pointer to the original variable.

Private Sub fooFunc (ByVal int1 As Integer, _
ByRef long1 As Long, _
long2 As Long) ' Passed ByRef by default

In the preceding VBA example, arguments long1 and long2 are both, by default, passed by reference. Modifying either argument within the body of the function modifies the original variable; however, modifying int1 does not modify the original because it is a copy of the original.

Previous Document Next Document Back to Top

Copyright 2013 Corel Corporation. All rights reserved.