9

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?

2
  • 2
    You might want to wait a little ( > 5 minutes) time before marking a question as answered to let more people make suggestions... ;-) Commented Feb 10, 2009 at 19:18
  • 2
    Why? The question was answered (I can always un-mark it as such). Commented Feb 13, 2009 at 22:33

5 Answers 5

14

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

Sign up to request clarification or add additional context in comments.

Comments

7

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

Comments

6

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

1 Comment

Here is the GOOD answer. Although you can't declare a constant array, there is a workaround: define it as a function.
1

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.