Objects stored in Variant variables
Objects can be stored in Variant variables. This can be useful when you need to efficiently handle various data types, including Objects. For example, all elements in an array must have the same data type. Set the data type of the array to Variant to store Objects together with other data types in the same array.
array
If you have experience programming in other languages, you must be familiar with the concept of arrays. Thanks to arrays, you can refer to a series of variables with the same name and identify them numerically (indexed). In many situations, using arrays can shorten and simplify programs because you can design a loop using index values to handle multiple situations efficiently. Arrays have upper and lower bounds, and the elements of the array are continuous within the upper and lower bounds. Because Visual Basic allocates space for each index value, do not declare an array that is unrealistically large.
Note that the arrays discussed in this section are arrays of variables declared in the program. They are different from control arrays, which are specified at design time by setting the Index property of the control. Variable arrays are always contiguous; unlike control arrays, array elements cannot be loaded or unloaded from the middle of an array.
All elements in an array have the same data type. Of course, when the data type is Variant, each element can contain different types of data (objects, strings, values, etc.). Arrays of any basic data type can be declared, including user-defined types (see "Creating your own data types" in Chapter 8, "Programming Again") and object variables (see Chapter 9, "Programming with Objects") .
There are two types of arrays in Visual Basic: fixed-size arrays - which always remain the same size, and dynamic arrays whose size can change at runtime. Dynamic arrays are discussed in detail in "Dynamic Arrays" later in this chapter.
Declare a fixed-size array
There are three ways to declare a fixed-size array, and which method you use depends on the valid range the array should have:
To create a public array, declare the array using the Public statement in the declaration section of the module.
To create a module-level array, declare the array using the PRivate statement in the declaration section of the module.
Create a local array and declare the array with the Private statement in the process.
Set upper and lower bounds
When declaring an array, the array name is followed by an upper bound enclosed in parentheses. The upper bound must not exceed the range of the Long data type (-2,147,483,648 to 2,147,483,647). For example, the following array declaration may appear in the declaration section of a module:
DimCounters(14)AsInteger '15 elements.
DimSums(20)AsDouble '21 elements.
To create a public array, directly replace Dim with Public.
PublicCounters(14)AsInteger
PublicSums(20)AsDouble
The same declaration uses Dim in the procedure: DimCounters(14)AsIntegerDimSums(20)AsDouble The first declaration creates an array with 15 elements, indexed from 0 to 14. The second declaration creates an array with 21 elements, indexed from 0 to 20. The default lower bound is 0.
To specify a lower bound, use the keyword To to provide an explicit lower bound (for the Long data type):
DimCounters(1To15)AsInteger
DimSums(100To120)AsString
In the preceding statement, Counters have index values ranging from 1 to 15, while Sums have index values ranging from 100 to 120.
Arrays containing other arrays
It is possible to create arrays of Variant data types and co-locate them with arrays of different data types. The following code creates two arrays, one containing integers and the other containing strings. Then declare a third Variant array and place the integer and string arrays in it:
PrivateSubCommand1_Click()
DimintXAsInteger 'Declare counter variable.
'Declare and place an array of integers.
DimcountersA(5)AsInteger
ForintX=0To4
countersA(intX)=5
NextintX
'Declare and place an array of strings.
DimcountersB(5)AsString
ForintX=0To4
countersB(intX)=hello
NextintX
DimarrX(2)AsVariant 'Declare a new array with two members.
arrX(1)=countersA() 'Move other arrays to the array.
arrX(2)=countersB()
MsgBoxarrX(1)(2) 'Display each array member.
MsgBoxarrX(2)(3)
EndSub
multidimensional array
Sometimes it is necessary to track relevant information in an array. For example, to track every pixel on a computer screen, you need to reference its X and Y coordinates. At this time, multidimensional arrays should be used to store values. Multidimensional arrays can be declared with Visual Basic. For example, the following statement declares a 10×10 two-dimensional array within a procedure.
StaticMatrixA(9,9)AsDouble
You can declare either or both dimensions with an explicit lower bound:
StaticMatrixA(1To10,1To10)AsDouble
All of this can be generalized to arrays of more than two dimensions. For example:
DimMultiD(3,1To10,1To15)
This declaration creates a three-dimensional array of size 4×10×15. The total number of elements is the product of the three dimensions, which is 600.
Note that when increasing the dimension of an array, the storage space occupied by the array will increase significantly, so multi-dimensional arrays should be used with caution. Be extra careful when using Variant arrays because they require larger storage space.
Using loops to manipulate arrays
You can use nested For loops to effectively process multi-dimensional arrays. For example, in MatrixA, each element is assigned a value based on its position in the array:
DimIAsInteger,JAsInteger
StaticMatrixA(1To10,1To10)AsDouble
ForI=1To10
ForJ=1To10
MatrixA(I,J)=I*10 J
NextJ
NextI
More informationFor more information about loops, see the "Loop Structures" section later in this chapter.
dynamic array
How large an array should be is sometimes unknown. So I hope to have the ability to change the size of the array at runtime.
Dynamic arrays can change size at any time. In Visual Basic, dynamic arrays are the most flexible and convenient, helping to manage memory effectively. For example, you can use a large array for a short time and then release the memory space to the system when the array is not in use.
If you don't use a dynamic array, declare an array with the largest size possible, and then erase unnecessary elements. However, if this method is used excessively, it will cause the memory operating environment to slow down.
To create a dynamic array, follow these steps:
1. (If you want the array to be a public array, then) declare the array with the Public statement, or (if you want the array to be a module level, then) declare the array with the Dim statement at the module level, or (if you want the array to be a local array, then) in Use the Static or Dim statement to declare the array during the procedure. Declare the array as dynamic by appending an empty dimension table to it.
DimDynArray()
2. Use the ReDim statement to allocate the actual number of elements.
ReDimDynArray(X 1)
ReDim statements can only appear within procedures. Different from Dim statement and Static statement, ReDim statement is an executable statement. Because of this statement, the application performs an operation at runtime. The ReDim statement supports a syntax that is the same as that used with fixed arrays. For each dimension, each ReDim statement can change the number of elements and the upper and lower bounds. However, the dimensions of the array cannot be changed.
ReDimDynArray(4to12)
For example, use the dynamic array Matrix1 created at the module level for the first time:
DimMatrix1()AsInteger
Then, allocate space for the array in the procedure:
SubCalcValuesNow()
.
.
.
ReDimMatrix1(19,29)
EndSub
The ReDim statement here allocates a 20×30 integer matrix to Matrix (total element size is 600). There is another way to use variables to set the boundaries of dynamic arrays:
ReDimMatrix1(X,Y)
Note that you can assign a string to a variable-sized byte array. A byte array can also be assigned to a variable-length string. It's important to note that the number of bytes in the string will vary with the platform. The same string has twice as many bytes on a Unicode platform as it does on a non-Unicode platform.
Preserve the contents of a dynamic array
Each time a ReDim statement is executed, all values currently stored in the array are lost. Visual Basic resets the value of an array element to Empty (for a Variant array), to 0 (for a Numeric array), to a zero-length string (for a String array), or to Nothing (for an array of objects).
This is useful when preparing an array for new data, or when you want to reduce the array size to save memory. Sometimes you want to change the size of an array without losing the data in the array. This can be done using the ReDim statement with the Preserve keyword. For example, using the UBound function to reference the upper bound causes the array to expand and add an element without losing the value of the existing element:
ReDimPreserveDynArray(UBound(DynArray) 1)
When using the Preserve keyword, you can only change the upper bound of the last dimension in a multidimensional array; if you change the lower bound of other dimensions or the last dimension, an error will occur at runtime. So it can be programmed like this:
ReDimPreserveMatrix(10,UBound(Matrix,2) 1)
Instead of programming like this:
ReDimPreserveMatrix(UBound(Matrix,1) 1,10)
For more detailed information about dynamic arrays, see "ReDim function" in the language reference. For information about object arrays, see Chapter 9, "Programming with Objects."
->