VBScript (or Visual Basic script) handles arrays very well. A VBScript programmer can quickly and easily:
- define an array
- populate the array with data
- iterate through the array
And VBScript is particularly useful for the programmer because it has a method for returning the maximum index number for an array. This method is called ubound, and this will even work with multidimensional arrays. However, there is a potential problem.
The number of dimensions is required by ubound but there is no method for calculating the number of dimensions in an array. Fortunately the VBScript programmer can write a function that will do the job. However, before doing that it is worth looking at simple and multidimensional arrays.
Working with a Simple Array in VBScript
The programmer creates a one dimensional array by defining its maximum index number:
In this example the array will have three elements (with index number 0, 1 and 2), and the elements can be populated with data:
If any more elements are written to then an error will occur, for example the following is illegal:
However, if the correct number of elements are populated then the programmer can use ubound to identify how many elements there are:
The result of this can be seen in figure 1 at the bottom of this article, and it's worth noting here that the default number of dimensions for ubound is one.
Working with a Multidimensional Arrays in VBScript
Multidimensional arrays are defined in a similar way to one dimensional arrays, and they require the maximum index number for each dimension:
Then each element in each dimension can be populated:
And again ubound can be used to calculate the number of elements that are in each dimension. However, this time ubound requires the dimension number:
The result of this can be seen in figure 2. Of course, there is an important question here. How can the programmer use ubound if they don't know how many dimensions there are?
A Function for Calculating Dimensions
If ubound is used with the wrong number of dimensions (for example if 3 in inputted but there are only 2 dimensions) then an error will occur. However, it is very easy to create a function that will make use of this error to identify the number of dimensions in a multidimensional array. The first step is to stop the function from exiting when the error occurs:
The maximum number dimensions allowed by VBScript is 32. It is, therefore, just a matter of counting the dimensions until an error occurs:
The number of dimensions that were counted before the error are then returned by the function:
And then the function can be used to calculate the number of dimensions that any array has, for example:
The result of this can be seen in figure 3, and the the function will accept variables that are not arrays:
In this way a VBScript programmer can easily find the number of dimensions in a multidimensional array, and it doesn't even matter if there are no dimensions or whether there are 32.