Working With Arrays in VBScript

As you progress to more and more complicated scripts, you will undoubtedly find yourself working with some form of data—perhaps a group of files, entries in a text file, or a group of dates. The possibilities are limitless. In any case, VBScript provides a few different facilities for handling and manipulating whatever kind of data you might be working with.

I’m quite sure you’ll find this explanation to be a bit vague, and that’s okay.  We’re going to jump right in and you’ll be up to speed in no time at all once you see these concepts in action.

We’ll begin by examining arrays.  An array is essentially VBScript’s list mechanism—a group of data items that are assigned to a single variable reference.  Many languages limit arrays to containing only text strings.  In VBScript, however, all variables are of type variant by default.  This extends to the array, which can house any data types, since they too are of type variant.

This means you could have an array of text strings — several text elements all assigned to the same variable reference.  You can also have an array of integer data.  More importantly, since we’re working with variants, you can have an array that mixes more than one data type.  Let’s take a look at how to create some arrays so you can see what we’re dealing with.

{mospagebreak title=Creating Arrays}

Arrays are typically created using the Dim statement.  The Dim statement reserves space in memory for a provided variable reference.  This statement is extended to allow creation of arrays.

Try to think of an array as a column in a spreadsheet.  An array contains several data elements, much like the individual cells in a spreadsheet.  You could, for instance, have a list of names.

Dim arrNames(2)

 

arrNames(0) = "John Doe"

arrNames(1) = "Jane Smith"

arrNames(2) = "Dick Tracy"

Here the Dim statement is used to create an array.  This is denoted by the number in parenthesis that follows the array name.  This number provides the Upper Boundary of the array.

Data elements are stored in an array in a zero-based fashion.  This means that each element can be referenced in the array by a number starting from zero.  So an array with an upper boundary of 2 can hold three elements: 0, 1, and 2.

We can assign values to these elements in just this fashion.  Notice how I’ve used the array name followed by the element’s number to assign these values.  Values in an array are read/write.

Dim arrNumbers(2)

 

arrNumbers(0) = 5

arrNumbers(1) = 25

arrNumbers(2) = 7

The first example created a String Array, or an array containing string values.  You can just as easily create an Integer Array, or an array containing integers.  Any valid variant value can be assigned to an array element.

Dim arrNames(2)

 

arrNames(3) = "Rob Dunham"

Be aware of your array’s boundaries.  Attempting to assign a value like this will result in a “subscript out of range” error because there is no element 3 in this array.

{mospagebreak title=Using Values from an Array}

Getting the data from an array is as easy as assigning the values to the array.  You’ll just need to use the array reference along with the number of the element for which you wish you read the value.

WScript.Echo "Hello,", arrNames(2) & "."

The arrNames(2) reference returns the value of the third element in the arrNames array, which contains the string “Dick Tracy”.  This results in the following output.

Hello, Dick Tracy.

Frequently you will want to process each element in an array.  To do this, you’ll want to iterate, or move through the array one element at a time.  This is typically done using a For…Next structure to loop through each element of the array.

For i = 0 To UBound(arrNames)

   WScript.Echo arrNames(i)

Next

In this example, I’ve introduced VBScript’s UBound function.  UBound returns the upper most boundary of an array.  In this case, it is the number 2.  Thus, the For…Next loop will move through each integer value from 0 to 2, assigning that value to the variable i.

The first time through, the loop will print the value of arrNames(0); the second time arrNames(1); and so on.  This method allows you to specify a starting and ending number so you can return any specific range of elements.

For Each strName In arrNames

   WScript.Echo strName

Next

You can also use VBScript’s For Each structure.  This will simply iterate through each element in the array, in order.

{mospagebreak title=Methods for working with arrays}

VBScript provides three different methods specifically for working with arrays.  The first is the Split method, which allows you to create an array from a delimited text string.

arrNames = Split("John Doe,Jane Smith,Dick Tracy", ",")

The first parameter is a text string from which to create an array.  The second parameter is a text string containing the delimiter that separates individual elements, in this case a comma.  In this example, arrNames would contain “John Doe”, “Jane Smith”, and “Dick Tracy”

John,Doe

Jane,Smith

Dick,Tracy

This concept can easily be extended to process comma- or tab-delimited text files.  Take for example the comma-delimited file above.  Each line of the file contains a unique name record that contains a first and last name separated by a comma.

Const ForReading = 1

Set objFso = CreateObject("Scripting.FileSystemObject")

Set objFile = objFso.OpenTextFile("C:names.csv", ForReading)

 

Do Until objFile.AtEndOfStream

   arrRecord = Split(objFile.ReadLine, ",")

   WScript.Echo "First Name:", arrRecord(0)

   WScript.Echo "Last Name:", arrRecord(1)

   WScript.Echo ""

Loop

You can use the FileSystemObject to open the file and read it into the script line by line.  The Split function is used to break out each piece of information.

VBScript also provides the Join function.  The opposite of the Split function, the Join function is used to create a delimited text string from an array.

Dim arrNames(2)

 

arrNames(0) = "John Doe"

arrNames(1) = "Jane Smith"

arrNames(2) = "Dick Tracy"

 

strNames = Join(arrNames, ",")

The first parameter is an array containing text elements to join together.  The second parameter is a text string indicating the text delimiter used to separate elements.

Finally, VBScript provides an Array method for creating arrays.  The nice thing about the array method is that it returns a dynamic array, as we’ll see a bit later.

arrNames = Array("John Doe", "Jane Smith", "Dick Tracy")

Each parameter passed to the array function becomes an element in the newly- created array.

{mospagebreak title=Dynamic and Multidimensional Arrays}

VBScript also allows you to create more advanced types of arrays: arrays whose sizes can be changed dynamically and arrays with multiple sets of elements.  These types of arrays allow you to process groups of data or dynamic data more easily.

A dynamic array is really not a new type of array.  It’s simply an array whose size can be changed dynamically.  This is accomplished through the use of the ReDim statement.

arrNames = Array()

ReDim arrNames(2)

 

arrNames(0) = "John Doe"

arrNames(1) = "Jane Smith"

arrNames(2) = "Dick Tracy"

In this example, I’m using the Array function to create an empty dynamic array.  Then I use the ReDim statement to resize the array before assigning values.

ReDim Preserve arrNames(3)

arrNames(3) = "Nilpo"

The ReDim statement will empty all elements in an array while resizing it.  You can prevent this by using the Preserve keyword.  If the size is being increased, it simply adds empty elements.  When decreasing, it will retain any elements that fit inside the new dimension and discard the rest.

This can be extended to create a very powerful mechanism for creating arrays dynamically.  For example, I could read a text file and assign each line of that file to an array element.  Since I may or may not know how many lines are in the text file, it’s quite handy to do this dynamically.

Const ForReading = 1

Set objFso = CreateObject("Scripting.FileSystemObject")

Set objFile = objFso.OpenTextFile("C:myfile.txt", ForReading)

 

arrLines = Array()

intCounter = 0

 

Do Until objFile.AtEndOfStream

   ReDim Preserve arrLines(intCounter)

   arrLines(intCounter) = objFile.ReadLine

   intCounter = intCounter + 1

Loop

 

objFile.Close

You can see here where I’m reading each line of a text file into an array.  I dynamically resize the array element (to increase its size by 1) before adding each new line.  The Preserve keyword ensures that existing data remains intact through each resize, and the intCounter variable is incremented to track the number of elements in the array.

ReDim Preserve arrNames( UBound(arrNames) + 5 )

There may also be times when you wish to resize an array without knowing how many elements it contains.  The example above adds five more elements to the arrNames array.  I’ve used the UBound function to return the upper boundary of the array and add 5 to that number.  The upper boundary represents the last element in the array.

Another advanced type of array is the multi-dimensional array.  This is like an array of arrays—each element contains a group of sub-elements in much the same way as each row of a worksheet contains several other columns.  For example, I could create an array of names.  Each element of that array would represent a person’s name, but would contain sub-elements that contain their first and last names separately.

Dim arrNames(2, 1)

 

arrNames(0,0) = "John"

arrNames(0,1) = "Doe"

 

arrNames(1,0) = "Jane"

arrNames(1,1) = "Smith"

 

arrNames(2,0) = "Dick"

arrNames(2,1) = "Tracy"

The syntax for a multi-dimensional array is the same as any other array.  You just add each additional dimension, separated by a comma.  The arrNames array contains three parent elements.  Each parent element contains two sub-elements as defined by the Dim statement.  Each element can then be accessed by providing the proper dimensions.  That’s why arrNames(2,1) represents the second sub-element of the third element in the arrNames array.

Dim arrNames(0)

arrNames(0) = Array("John", "Doe")

 

WScript.Echo arrNames(0,1)   ‘Does not work

WScript.Echo arrNames(0)(1)  ‘Does work

In this example, I’ve attempted to create a multi-dimensional array by assigning an array to another array element.  This code works perfectly; however, I cannot access the sub-elements as I should be able to.  Why?  A multi-dimensional array is like an array of arrays—it’s not actually the same thing.  This code adds an array reference to the first array, but does not actually add the second array’s data.  This is still stored in memory in the second array.  All I’ve really done here is nest two arrays.

As you can see, there are several ways to utilize arrays in VBScript.  They can be very powerful mechanisms for accessing and processing data, but you have to be sure that they are created and handled properly.  Go ahead and play around with these code samples.  You’ll gain a better understanding through trial and error.  Until next time, keep coding!

[gp-comments width="770" linklove="off" ]