Search code examples
arraystypesvbscriptmismatch

VBS Array in its most simple way


I can't create an undefined array in VBS.

It should be as long as needed. I don't want to declare some limit like 10 or so, with Dim arrnode(10). I need an unlimited one.

I tried:

Dim arrnode    
arrnode(1) = "a"     
arrnode(2) = "b"     
arrnode(3) = "c"     
arrnode(4) = "d" 

And lots of variations like:

Dim arrnode()   
Dim arrnode() As Variant
Dim arrnode() As Variant()

Etc.etc. None of this works. Errors only.

Please give an example that works. I'm not looking for an explanation as I can't understand the "variant" explanation I found over and over on the web. I'm just desperately in need of a very simple array that works.


Solution

  • There are different ways to create arrays in VBScript

    Arrays with defined size

    Dim arrTest1(3)
    arrTest1(0) = "1"
    arrTest1(1) = "2"
    arrTest1(2) = "3"
    arrTest1(3) = "4"
    

    Arrays without defined size

    Dim arrTest2()
    ReDim arrTest2(3)
    arrTest2(0) = "1"
    arrTest2(1) = "2"
    arrTest2(2) = "3"
    arrTest2(3) = "4"
    

    Using Array function to create an array

    Dim arrTest3
    arrTest3 = Array ("1", "2", "3", "4")
    

    In VBScript, arrays starts from zero and you can't define the variable type (e.g. as Variant) while declaring arrays

    You can use the second option if you are not sure about the size of array. You can always ReDim it later on to change its size. Don't forget to use Preserve keyword if you want to protect the array data if you are ReDiming it