Return values from multidimentsional array

G

Guest

I am having trouble figuring out how to return values from the first
dimension of a multidimensional array. Below is an example that I was
playing with:

************************************************************

Sub ArrayTest()
Dim Array1() As Variant

ReDim Array1(0)

Array1(0) = "Test"
ReDim Array1(0, 0)

Array1(0, 0) = "Test2"

MsgBox Array1(0)
End Sub
***********************************************************
I am trying to return the value 'Test' in the msg box but I get an Subscript
is out of range error. Can anyone help me out with the syntax of how to do
this?

Thanks,
Chad
 
R

RB Smissaert

You simply need MsgBox Array1(0, 0) instead of MsgBox Array1(0)
as you now have a 2-D array, not a 1-D array.

RBS
 
J

JE McGimpsey

When you ReDim Array1(0, 0), any values previously assigned to Array1
are lost.

Values aren't stored in 'dimensions', so you can't return "values from
the first dimension of a multidimensional array". Instead each dimension
provides an index into the array.

When you declare Array1(0, 0), you're creating an array with a single
element with index (0,0).

Likewise,

Dim Array2(0 to 1, 0 to 1)

declares a four-element array. Each element requires two indices to
specify it:

Array2(0, 0), Array2(0, 1), Array2(1, 0), Array2(1, 1)

Array2(0) has no meaning in that context, and will generate the
Subscript out of range error you're seeing.
 
I

ilia

Change

MsgBox Array1(0)

to

MsgBox Array1(0, 0)

you redimmed it therefore it now has two dimensions and "Test" is gone
(array is deleted on redim).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top