OutOfBounds Exception loading array

I keep getting an OutOfBounds Exception when trying to load an array. I have read the documentation and it appears I am performing the steps correctly… none of the other out of bound exception posts seem to address my circumstance.

For Each row As DatabaseRow In rsInvest
  If( strCompare <> rsInvest.Column( "investCompany" ).StringValue ) Then
    strArySorter( i ) = rsInvest.Column( "investCompany" ).StringValue // <-- Exception occurs here.
    i = i + 1
  End If
  strCompare = rsInvest.Column( "investCompany" ).StringValue
Next

How are you declaring strArraySorter?

Or just use:

StrArySorter.Add rsInvest.Column( "investCompany" ).StringValue
3 Likes

Var strArySorter( ) As String

Your solution worked, but when I look at the documentation for Array it doesn’t show that style?

Now I have a new issue…

I am now wanting to add the array contents to a combination box… and it’s showing OutOfBounds exception too!

Var A As Integer
While A < i
  Me.AddRow strArySorter( i ) // <-- here it is!
  A = A + 1
Wend

You need to redefine “i” properly before running that code.

In this code below, “i” will always 1 greater than the number of rows in rsInvest, because “i” is incremented at the end of the loop, even if it doesn’t start a new loop.

For Each row As DatabaseRow In rsInvest
  If( strCompare <> rsInvest.Column( "investCompany" ).StringValue ) Then
    strArySorter( i ) = rsInvest.Column( "investCompany" ).StringValue // <-- Exception occurs here.
    i = i + 1
  End If
  strCompare = rsInvest.Column( "investCompany" ).StringValue
Next

And here, “i” never changes, so strArySorter( i ) is always going to be the same.

Var A As Integer
While A < i
  Me.AddRow strArySorter( i ) // <-- here it is!
  A = A + 1
Wend

This will work:

 For i as integer = 0 to strArySorter.LastIndex
 Me.AddRow strArySorter( i )
 Next i

Hmm, thanks I learned something new about Arrays. Your solution worked perfectly. Much appreciated!

You don’t actually need i at all

For Each row As DatabaseRow In rsInvest
  If( strCompare <> rsInvest.Column( "investCompany" ).StringValue ) Then
    strArySorter.AddRow(rsInvest.Column( "investCompany" ).StringValue)
   End If
  strCompare = rsInvest.Column( "investCompany" ).StringValue
Next

Will just add the value to the end of the array assuming the array size was undefined.

1 Like