Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Westi on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Redim Multidimensional Array 1

Status
Not open for further replies.

nigz

Programmer
Jun 15, 2001
60
GB
Why am I getting a 'subscript out of range' message on the following:

ReDim Preserve a_invoice(UBound(a_invoice,1) + 1, 5)

when

ReDim a_invoice(0,5) haspreviously been set and UBound(a_invoice,1)
gives a sensible value - it's driving me nuts.......thanks - Nigz

 
Hi,

you can only change the last dimension of the array with the preserve statement. The following is what MSDN states:

Preserving the Contents of Dynamic Arrays
Each time you execute the ReDim statement, all the values currently stored in the array are lost. Visual Basic resets the values to the Empty value (for Variant arrays), to zero (for numeric arrays), to a zero-length string (for string arrays), or to Nothing (for arrays of objects).

This is useful when you want to prepare the array for new data, or when you want to shrink the size of the array to take up minimal memory. Sometimes you may want to change the size of the array without losing the data in the array. You can do this by using ReDim with the Preserve keyword. For example, you can enlarge an array by one element without losing the values of the existing elements using the UBound function to refer to the upper bound:

ReDim Preserve DynArray(UBound(DynArray) + 1)

Only the upper bound of the last dimension in a multidimensional array can be changed when you use the Preserve keyword; if you change any of the other dimensions, or the lower bound of the last dimension, a run-time error occurs. Thus, you can use code like this:

ReDim Preserve Matrix(10, UBound(Matrix, 2) + 1)

But you cannot use this code:

ReDim Preserve Matrix(UBound(Matrix, 1) + 1, 10)

Herman :-Q
 
Hi

You can only change the size of the last dimension.
From MSDN:

If you use the Preserve keyword, you can resize only the last array dimension and you can't change the number of dimensions at all. For example, if your array has only one dimension, you can resize that dimension because it is the last and only dimension. However, if your array has two or more dimensions, you can change the size of only the last dimension and still preserve the contents of the array. The following example shows how you can increase the size of the last dimension of a dynamic array without erasing any existing data contained in the array.


Sunaj
 
Sorry Herman

I didn't see your post before I wrote mine...

Sunaj
 
Thanks Guys - you live & learn eh! ;) - I'll just have to think of another to do it - Nigz
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top