Search code examples
arraysvbscriptasp-classic

Why am I getting "subscript out of range" when the subscript IS in the range?


I'm working with some legacy spaghetti code that processes some hairy EDI. Most of the code is indecipherable and has no indentation or comments or even good variable names but there's one line that gives me trouble when I remove the On Error Resume Next statement which causes the script to always timeout.

If UBound(arylin) >= 1 Then
    Do Until arylin(0) = "PB" and arylin(1) = "DEF"
        ' Processing goes here - not relevant for this
    Loop
End If

The script executes the conditional but errors at the "Do Until" line, saying:

Microsoft VBScript runtime error '800a0009' 

Subscript out of range: '[number: 0]' 

Now, why on Earth would this be giving an error if I'm testing the upper bound before checking it, and it's saying that the upper bound is at least 1?

I can post more of the code if I have to but I'd rather not since my predecessor was a complete hack and the code is extremely ugly.


Solution

  • UBound() returns the index of the last element in the array. By default, arrays in vb languages prior to vb.net start at 1 rather than 0 (meaning the count and the index are normally the same thing, though you can change the default with Option Base).

    Put those together you'll see that it's failing here:

    arylin(0) = "PB"