2 dimensional array

Hi All,

I got an “out of bounds exception” for:

Dim a (-1,-1) as string
for x = 0 to rs.FieldCount-1
a(x, 0) = rs.IdxField(x+1).Name
next

However, if I changed the array declartion to a(20,2), it works perfectly.

Anything I did wrong?

Yes. With Dim a (-1, -1) you define a 2dim array with 0 elements in both dimensions. You need to make sure the array has enough elements to fit your demands.
Out of curiosity: What do you store inside it? Wouldn’t a dictionary do too?

You probably need to dimension your array something like this prior to assigning data to it:

Dim a ( rs,fieldcount-1, rs.recordcount-1) as string

Be careful with rs.recordcount. it does not work reliably with all databases and all connexion methods. Sometimes, I redim arrays on the fly also when the dimensions are not easily predictable.

Keep in mind too that redimensioning is an expensive operation so try to do it as few times as possible. If you know how many elements you will need, fine, but if you don’t, one strategy is to make it something far larger than you’d need, then trim it after you’re done.

For example:

dim a( 50, 50 ) as string // 50 is arbitrary
dim trueX as integer = -1
dim trueY as integer = -1

//
// Now we start adding elements
//

if Ubound( a, 1 ) < x then
  redim a( x * 2, Ubound( a, 2 ) )
end if

if Ubound( a, 2 ) < y then
  redim a( Ubound( a, 1 ), y * 2 )
end if

a( x, y ) = something
trueX = max( trueX, x )
trueY = max( trueY, y )

Every time you add an element larger than the current size of the array, it redimensions to twice that size. At the end, you can trim the array to just what you need using trueX and trueY.

I recently used this strategy to cut down the running time of a method from about 55 seconds to 12.

Thanks all for your advice.

I agree with Ulrich: depending on what you do a dictionary might be better.

Or a Class. Or parallel arrays. Almost anything is easier to work with than a multidimensional array.

Or an array of classes :wink: