Wednesday, 2 July 2014

Understanding Arrays in VBscript

Understanding Arrays

One fundamental scripting technique is to store data in an array and then use the data in a 
script. Arrays can be very complicated and multidimensional, but for our purposes, we keep 
them simple and basic. Think of an array as a collection of buckets, each bucket holding one 
piece of information. When we need that piece ofinformation, we retrieve it from its bucket. 
Each bucket has a number, starting with 0.
There are a few ways to get information into an array. One way is to use the Arrayfunction.
myArray=Array("Elm","Maple","Oak","Walnut","Hickory","Pine")
This technique works well when the information to be stored is known ahead of time 
and there is a relatively small amount of it. For a more dynamic approach, we use the Split
function.

strText="Elm,Maple,Oak,Walnut,Hickory,Pine" 
myArray=Split(strText,",")

The Splitfunction takes the specified text string and splits each element, in this case separated 
by a comma, into the individual buckets of the array.
After we have data in the array, we can access a bucket directly if we know its number. Thus if 
we want to use Walnut, we would reference myArray(3).Even though humans would count 
Walnutas the fourth element, because we typically start counting at 1, the array starts counting at 0. Thus the UBound(myArray)function, which displays the upper limit of the array, 
returns 5. If we want to return a human-friendly count of the array elements, we need to use 

UBound(myArray)+1.
To go through every element in the array, we can use a For…Nextloop, as follows.
For i=0 To UBound(myArray) 
WScript.EchomyArray(i) 
Next

Typically we pass the value from the array to a subroutine or function elsewhere in the script. 
We’ll give you a sample later.

No comments:

Post a Comment