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?
An array is the result of a function call (Array()
) in VBScript. Only literal values can be made Const
. So: No, you can't.
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
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
Simple answer: no. The array cannot be made const
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With