Working With Arrays in VBScript - Using Values from an Array
(Page 3 of 5 )
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.
Next: Methods for working with arrays >>
More Windows Scripting Articles
More By Nilpo