1

I have this code in VBS:

Dim Arg()
Set objArgs = WScript.Arguments
for i=0 to objArgs.Count
  Arg(i) = Replace(objArgs(i),"\n",vbNewLine,1,-1,1)
... (yes, the for has a Next at the end)

(example arguments: "hello\nworld" "test" 0 64)

But when I run it, it throws an error: The subscript is out of range (line 4, column 3).

Am I incorrectly using the arrays, or is the problem in the for, or what is wrong?

3
  • 5
    Indexing starts at 0 but Count is 1 larger than the last index. objArgs.Count - 1 Commented Jul 22, 2022 at 22:07
  • from i=0 to objArgs.Count-1? Commented Jul 23, 2022 at 8:26
  • 2
    If you have 0 to 9 for example the count of the array elements would be 10. So at the moment you are looping 0 to 10 where the 11th element doesn’t exist hence the subscript out of range error. Commented Jul 23, 2022 at 9:51

1 Answer 1

3

Arrays in VBScript are zero ordinal based that means that if you have for example ten elements in the array they will be numbered zero to nine.

So when using Count it will return the number of elements not their position in the array so you will need to minus one from the Count or VBScript will report a "Subscript out of range" error as there is no 11th element in the array to iterate to.

As suggested in the comments, you want to do this;

For i = 0 To objArgs.Count - 1

The other issue is you declare a dynamic array (Dim Args()) but never initialise it before trying to insert elements into it. You could see this answer to a similar question that explains the problem. When using a dynamic array declaration you need to initialise it using ReDim.


Useful Links

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

8 Comments

same error, even tho i changed it
I think the other problem is the use of Dim Args(). See subscript out of range while adding items to array
that was the problem: dimming things without a fixed length
You don’t need to have a fixed length, ReDim Preserve allows to dynamically increase the array as you go while still maintaining the existing data.
then i can dim Arg() with ReDmin Preserve?
|

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.