aritz331_
aritz331_

Reputation: 68

Subscript out of range error (with array)

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?

Upvotes: 1

Views: 1364

Answers (1)

user692942
user692942

Reputation: 16671

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

Upvotes: 3

Related Questions