简体   繁体   中英

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?

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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM