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")
Author by
jon rios
Updated on July 09, 2022Comments
-
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 almost 7 yearsOr, if you want to have it all in a single line, use
Dim arr : arr = Array("sample 1", "sample2", "sample 3")
. -
Stevoisiak over 6 yearsWhat are the
>>
marks for? They make the code a bit harder to read. -
Ekkehard.Horner over 6 years
>>
is the prompt of my REPL. -
Passer-by about 4 yearsI 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 about 4 yearsYou can't have native base 1 arrays in VBScript. Just adapt your access code.