How does one declare an array in VBScript?

31,240

Solution 1

VBScript's (variables and) arrays can't be typed, so no "as Whatever". VBscript's arrays are zero-based, so no "(x To y)" but only "(z)" where z is the last index (not the size) of the array. In code:

>> Dim varScreen(2)
>> varScreen(0) = "sample 1"
>> varScreen(1) = "sample 2"
>> varScreen(2) = "sample 3"
>> WScript.Echo Join(varScreen, "|")
>>
sample 1|sample 2|sample 3
>>

Solution 2

You can also create arrays dynamically using the Array function. Sometimes this is more convenient than assigning array elements separately.

Dim arr
arr = Array("sample 1", "sample2", "sample 3")
Share:
31,240
jon rios
Author by

jon rios

Updated on July 09, 2022

Comments

  • jon rios
    jon rios almost 2 years

    I used this in Excel and it works fine.

    dim varScreen (0 to 2) as string
    varScreen(0) = "sample 1"
    varScreen(1) = "sample 2"
    varScreen(2) = "sample 3"
    

    I am trying to translate this array to VBScript but I keep getting this error:

    Line: 14
    Error: Expected ')'
    

    I have tried various options, removed as string, dim varScreen as array but I still get the error.

    What is the proper syntax?

  • Cellcon
    Cellcon almost 7 years
    Or, if you want to have it all in a single line, use Dim arr : arr = Array("sample 1", "sample2", "sample 3").
  • Stevoisiak
    Stevoisiak over 6 years
    What are the >> marks for? They make the code a bit harder to read.
  • Ekkehard.Horner
    Ekkehard.Horner over 6 years
    >> is the prompt of my REPL.
  • Passer-by
    Passer-by about 4 years
    I encountered similar problem by writing (1 To n), which works fine in vba, I just wanted my array to have base 1, so how can I realize base 1 not from 0? Thanks!
  • Ekkehard.Horner
    Ekkehard.Horner about 4 years
    You can't have native base 1 arrays in VBScript. Just adapt your access code.