Microsoft Office Tutorials and References
In Depth Information
Figure 9-3. An object variable in memory
Further, if we were to write:
Dim iVar2 As Integer
iVar2 = iVar
iVar2 = 567
we would not expect the last line of code to have any effect upon the value of the variable iVar ,
which should still be 123. This is because iVar and iVar2 represent different areas of memory,
as pictured in Figure 9-2 .
However, an object variable is not the name of a memory location that holds the object. Rather, an
object variable is the name of a memory location that holds the address of the memory location
that holds the object, as shown in Figure 9-3 . Put another way, the object variable holds a
reference to or points to the object. For this reason, it is an example of a pointer variable , or
simply a pointer . In Figure 9-3 , the object variable rng points to an object of type Range, namely,
the first column in the active sheet.
Figure 9-3. An object variable in memory
The code that goes with Figure 9-3 is:
Dim rng as Range
Set rng = ActiveSheet.Columns(1)
One of the consequences of the fact that object variables are pointers is that more than one object
variable can point to (or refer to) the same object, as in:
Dim rng as Range
Dim rng2 as Range
Set rng = ActiveSheet.Columns(1)
Set rng2 = rng
This code creates the situation pictured in Figure 9-4 .
Figure 9-4. Two object variables referencing the same object
We emphasize that while rng and rng2 are different object variables, they hold the same value
and so, point to the same object. Thus, we can change the first column using either of these object
variables.
It is important when programming with objects to keep very careful track of all object variables
and what they are referencing. Furthermore, it is generally not a good idea to have more than one
object variable pointing to the same object (as in Figure 9-4 ) unless there is a compelling reason to
do so. It is very easy to change the object using one object variable (say rng ) and then later use
the other variable ( rng2 ), thinking it refers to the unchanged object.
 
 
 
 
Search JabSto ::




Custom Search