This is the next tutorial in the VBScript Tutorials for Beginners. This VBScript beginner tutorial explains the VBScript array variable. Please view the VBScript tutorial 7 or read on... What is array in VBScript? An array variable in VBScript can store multiple values in it. Such data values may be customer names or phone numbers or email addresses etc. A VBScript array has indexes to refer the different values in it. The indexes start with the index 0. In the VBScript example below, the Sub FixedArray shows an array example, strCustomers(3). We can run this VBScript in the Command Prompt using the CScript command e.g. CScript Array1.vbs
' VBScript code
Option Explicit
Call FixedArray
Call DynamicArray
Sub FixedArray
' Declare a fixed array i.e. an array with the specified number of elements.
Dim strCustomers(3)
strCustomers(0) = "Abe"
strCustomers(1) = "Ben"
strCustomers(2) = "Chris"
strCustomers(3) = "Dustin"
' Display the first data value in the command window, instead of a message box.
WScript.Echo "strCustomers(0) is " & strCustomers(0)
End Sub
Sub DynamicArray
' Declare a dynamic array i.e. an array whose number of elements is unknown at present.
Dim strCustomersNew()
' VBScript Redim statement defines the number of elements in the array.
Redim strCustomersNew(3)
strCustomersNew(0) = "Abe"
strCustomersNew(1) = "Ben"
strCustomersNew(2) = "Chris"
strCustomersNew(3) = "Dustin"
' Preserve in the Redim statement retains the existing array elements.
Redim Preserve strCustomersNew(5)
strCustomersNew(4) = "Eddie"
strCustomersNew(5) = "Fred"
Dim i
' VBScript UBound function gives the upper bound of the array.
For i = 0 to UBound(strCustomersNew)
WScript.Echo "The element" & i & " is " & strCustomersNew(i)
Next
End Sub
' VBScript code
Option Explicit
Call FixedArray
Call DynamicArray
Sub FixedArray
' Declare a fixed array i.e. an array with the specified number of elements.
Dim strCustomers(3)
strCustomers(0) = "Abe"
strCustomers(1) = "Ben"
strCustomers(2) = "Chris"
strCustomers(3) = "Dustin"
' Display the first data value in the command window, instead of a message box.
WScript.Echo "strCustomers(0) is " & strCustomers(0)
End Sub
Sub DynamicArray
' Declare a dynamic array i.e. an array whose number of elements is unknown at present.
Dim strCustomersNew()
' VBScript Redim statement defines the number of elements in the array.
Redim strCustomersNew(3)
strCustomersNew(0) = "Abe"
strCustomersNew(1) = "Ben"
strCustomersNew(2) = "Chris"
strCustomersNew(3) = "Dustin"
' Preserve in the Redim statement retains the existing array elements.
Redim Preserve strCustomersNew(5)
strCustomersNew(4) = "Eddie"
strCustomersNew(5) = "Fred"
Dim i
' VBScript UBound function gives the upper bound of the array.
For i = 0 to UBound(strCustomersNew)
WScript.Echo "The element" & i & " is " & strCustomersNew(i)
Next
End Sub
Next, let us see the VBScript code with an array of numbers.
