VBScript Arrays

A VBScript array is a special type of variable that allows you to store multiple values against a single variable.

For example, say you have a shopping list that you want to store and write out to the screen. You could store these in a simple variable like this:

item1 = "Bananas"
item2 = "Bread"
item3 = "Pasta"

This will work fine. But one problem with this approach is that you have to write out each variable name whenever you need to work with it. Also, you can't do things like, loop through all your variables. If these values were stored in an array, you could save yourself a lot of time.

What Does an Array Look Like?

Arrays can be visualized as a stack of elements. Each element has an index number (left column) and a value (right column).

Note that VBScript arrays start their numbering at zero.


Creating Arrays in VBScript

VBScript arrays are created by first assigning an array object to a variable name...

Dim arrayName(numberOfElements)

then by assigning values to the array...

arrayName(0) = "Array element 1"
arrayName(1) = "Array element 2"
arrayName(2) = "Array element 3"

So, using our prior example, we could write:

Dim shoppingList(3)
shoppingList(0) = "Bananas"
shoppingList(1) = "Bread"
shoppingList(2) = "Pasta"

Accessing Array Data

You can access data in an array by referring to the name of the array and the element's index number.

Display a Single Array Element

This example displays the second element of the array named shoppingList (remember that VBScript array index numbers begin at zero). In this case, the value would be Bread


So, building on our previous example, you could use the following code to declare an array, assign values, then output the contents to the screen.

Dim shoppingList(3)
shoppingList(0) = "Bananas"
shoppingList(1) = "Bread"
shoppingList(2) = "Pasta"

This results in:


Modify the Contents of an Array

You can modify the contents of an array by specifying a value for a given index number:

shoppingList(1) = "Wholemeal Bread"

Now, the value of the second element will be:

Wholemeal Bread