Working With Arrays in VBScript - Methods for working with arrays
(Page 4 of 5 )
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.
Next: Dynamic and Multidimensional Arrays >>
More Windows Scripting Articles
More By Nilpo