An Array is a data structure which can hold multiple variables of the same type. So far whatever the examples we have seen in the previous posts we have used variables for each value.
Here, variable a and the variable b are multiplied and the result is stored back in the variable ans.
Let us have a look at the below example:
x=10 y=10 ans=x*y msgbox ans ans=20 msgbox ans
In this small script, variables x & Y are initialized with value 10. The variables x & y are multiplied and the result is stored in another variable ans. After value of the variable ans is displayed using msgbox, it is re-initialized with the statement “ans=20”. Again the value of ans is displayed using msgbox.
Value of ans before re-initialization – 100
Value of ans after re-initialization – 20
Each variable can hold a single value and whenever it is reinitialized holds the new value.
If we want to assign more than a single value to a variable then array should be used as a data type.
Dim arr(5) arr(0)=10 arr(1)=15 arr(2)=60 arr(3)=20 arr(4)=50 arr(5)=55 For i=0 to 5 msgbox "Arr("&i&") : "&arr(i) Next
Save the script as arrayexample.vbs and execute the script.
Dim array_name(number of values)
As we can see in the above example, array index starts with 0. Hence, array declared as arr(5) holds six values.
Now, we will try to initialize more than the declared values (i.e. declared as arr(5), and try to initialize arr(6))
Dim arr(5) arr(0)=10 arr(1)=15 arr(2)=60 arr(3)=20 arr(4)=50 arr(5)=55 arr(6)=25 For i=0 to 5 msgbox "Arr("&i&") : "&arr(i) Next
When the above script is executed, it throws error “Subscript out of range”.
This behavior of the array can be overcome with usage of dynamic arrays. We will discuss the dynamic arrays in the next post.