Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you declare a constant array in VBScript?

Tags:

vbscript

I want to use an array that I declare once at the top of my code several times. Ex.

Const Quarters = ["Q1", "Q2", "Q3", "Q4"]

For each Quarter q q.Do some work

Etc.

Can this be done in VBScript?

like image 756
user45492 Avatar asked Feb 10 '09 18:02

user45492


5 Answers

An array is the result of a function call (Array()) in VBScript. Only literal values can be made Const. So: No, you can't.

like image 197
Tomalak Avatar answered Nov 13 '22 01:11

Tomalak


Why not just declare the array as public and then assign the array during the start of the script?

Public arrQuarters
arrQuarters = Array("Q1", "Q2", "Q3", "Q4")

For Each Quarter in arrQuarters
    wscript.echo Quarter
Next
like image 37
Dscoduc Avatar answered Nov 13 '22 01:11

Dscoduc


You could define a function to return the array you want to use as a constant. For example:

For Each q in AllQuarters
    wscript.echo q
Next

wscript.echo "element 0 = " & AllQuarters()(0)

AllQuarters()(0) = "X1"

wscript.echo "element 0 still = " & AllQuarters()(0)


Function AllQuarters()
    AllQuarters = Array("Q1","Q2","Q3","Q4")
End Function
like image 26
NYCdotNet Avatar answered Nov 13 '22 01:11

NYCdotNet


Simple answer: no. The array cannot be made const.

like image 22
Konrad Rudolph Avatar answered Nov 13 '22 01:11

Konrad Rudolph


A shorter and less error-prone solution would be:

Dim arr
arr = Split("Q1 Q2 Q3 Q4") : ubd = UBound(arr)
' Implied separator is " " aka 040 octal aka 32 Dec aka 020 Hex.

If your data might contain spaces:

arr = Split("Le Sage,ne pleure,ni les vivants, ni les morts", ",")
ubd = UBound(arr)
' arr(2), for instance, now contains "ni les vivants"

Caution: Never choose a separator that might occur in your 'atomic' data strings, or the function will split on that separator in the middle of a single piece of data.

like image 43
LeChatDeNansen Avatar answered Nov 13 '22 01:11

LeChatDeNansen