This section provides a tutorial example on how to use an array reference like an array to access referenced array elements, to re-size the referenced array, and to pass the referenced array into functions.
After learning that a scalar variable can be used to store the reference of an array,
let's try to learn more about array reference:
An array reference is a scalar value. This is why it can be assigned to a scalar variable.
A scalar variable holding an array reference can be used like an array variable.
"array_reference(i)" represents the element of index i of the referenced array.
"ReDim Preserve array_reference(n)" resets the size of the referenced array.
When an array reference is used as a function argument, the referenced array is passed
into the function, not the reference. For example, "TypeName(array_reference)" returns
Variant().
To show you how an array reference works
I wrote the following example, array_reference.html:
<html>
<body>
<!-- array_reference.html
- Copyright (c) 2015, HerongYang.com, All Rights Reserved.
-->
<pre>
<script language="vbscript">
Dim aReference
Dim anArray(1)
anArray(0) = "Dog"
anArray(1) = "Cat"
aReference = anArray 'An array reference is assigned
aReference(0) = "Pig" 'Accessing an element through the reference
ReDim Preserve aReference(2) 'Re-sizing the referenced array
aReference(2) = "Fox"
upperLimit = UBound(aReference) 'The referenced array is passed
document.writeln("TypeName(aReference): " & TypeName(aReference))
document.writeln("UBound(aReference): " & upperLimit)
For Each e In aReference
document.writeln(" " & e )
Next
</script>
</pre>
</body>
</html>
Here is the output:
TypeName(aReference): Variant()
UBound(aReference): 2
Pig
Cat
Fox
The output confirms that all notes mentioned earlier in this section are true.