Scripting Home > VBScript Reference

Arrays - Working with Arrays


Arrays are used to group and store a set of variables together in one object. VBScript supports both simple and multi-dimensional arrays with up to 60 dimensions.

Defining Arrays
Arrays are created in a similar way to standard variables except that you can optionally define the number of elements and dimensions. For example to create an array with 5 elements the command would be:

Dim MyArray(4)

Since all arrays start with the index number zero it is counted as the first number, there this array very though it was defined as MyArray(4) contains five elements: 0, 1, 2, 3, 4.

Using Arrays
The array's index numbers are used to both set and retrieve data from the array. For example to set an array value you could use the following command:

MyArray(0) = "First element"
MyArray(1) = "Second Element"

Then to retrieve and echo the data you could use:

WScript.echo MyArray(1)

Multi-Dimensional Arrays
You can create multi-dimensional arrays by seperating the size of each dimenion with commas, for example:

Dim MultiArray(4,5)

Sizing Arrays
VBScript creates static arrays, i.e. the size must defined prior to use, therefore to resize an Array you must use the ReDim function.

For example, in a function where the size of the array will be based on the number of variables, you could use the following command to resize it:

ReDim Preserve MyArray(count - 1)

Note: Use the Preserve keyword to prevent the contents of the array being lost when using the ReDim function.