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?

aritz331_
  • 68
  • 2
  • 9
  • 5
    Indexing starts at 0 but `Count` is 1 larger than the last index. `objArgs.Count - 1` – Rno Jul 22 '22 at 22:07
  • `from i=0 to objArgs.Count-1`? – aritz331_ Jul 23 '22 at 08: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. – user692942 Jul 23 '22 at 09:51

1 Answers1

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

user692942
  • 16,398
  • 7
  • 76
  • 175