Why am I getting "index out of range" when IS index is in range?

I am working with some old spaghetti code that handles some hairy EDI. Most of the code is illegible and has no indentation or comments or even good variable names, but there is one line that causes me problems when I remove a statement On Error Resume Next

that calls the script always time out.

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 conditional but errors on the "Do Until" line, saying:

Microsoft VBScript runtime error '800a0009' 

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

Now, why on Earth would it give an error if I check the upper bound before checking it and it says the upper bound is at least 1?

I can post more code if I need to, but I would prefer it since my predecessor was a complete hack and the code is very ugly.

+2


source to share


2 answers


UBound()

returns the index of the last element in the array. By default, arrays in vb through vb.net start at 1, not 0 (this means that the number and index are usually the same, although you can change the default with Option Base

).

Put them together, you can see that it doesn't work here:



arylin(0) = "PB"

      

+2


source


See AnthonyWJones comment)
(With VB you can set the base of arrays to start at 0 or 1 - it should be at or near the top of the module: look for Option Base 1 or Option Base 0.)

LBound will always return 0. (You can also use LBound () to check the lower bound of an array.)
(Just goes to show: don't expect MS to be consistent!)

Although you are checking that the size of the array is> = 1, which ensures that arylin (0) is valid, but not necessarily arylin (1). The index is zero based, so if one element exists it will be at index = 0 and index = 1 will be out of bounds.



In this case, you must check the size of the array> = 2. If you use two records sequentially one after the other, then you must check (size of the array) mod 2 = 0.

Also make sure the UBound value is actually returned. I googled and got conflicting information: this says it returns "count" and this one says it returns the physical limit (= 'count' -1).

About the "Accept error message further" error, maybe it should stay there ...

+3


source







All Articles