1. ## Array Element (03)

I am having a challenge displaying the elements in an array.

Dim myArray

myArray = Range("MyRange")
For x = 0 to UBound(myArray)
Msgbox myArray(x)
Next

Thanks,
John

2. ## Re: Array Element (03)

If you assign a range to a variant that way, you get an array that is 1 based - i.e. the lower bound is 1 not 0. Try replacing <code>For x = 0 to UBound(myArray)</code>
with either:
<code>For x = 1 to UBound(myArray)</code>

or
<code>For x = LBound(myArray) to UBound(myArray)</code>

Edited to add: I just noticed that you have only used one dimension in your Msgbox statement. A range passed to a variant creates a two-dimensional array so you need to use something like:
<code>Msgbox myArray(x, 1)</code>

HTH

3. ## Re: Array Element (03)

Further to my last post, if you don't know how many columns you have and you want to iterate through all values, you would use something like:
<pre> Dim myArray, x As Long, y As Long
myArray = Range("MyRange")
For x = LBound(myArray, 1) To UBound(myArray, 1)
For y = LBound(myArray, 2) To UBound(myArray, 2)
MsgBox myArray(x, y)
Next y
Next x

</pre>

HTH.

4. ## Re: Array Element (03)

Rory,

Thanks for the explanation. It worked.

John

5. ## Re: Array Element (03)

A range is a two-dimensional array, even if it consists of only one row or column. And better use LBound too.

Dim myArray
Dim x As Integer
Dim y As Integer
myArray = Range("MyRange")
For x = LBound(myArray, 1) To UBound(myArray, 1)
For y = LBound(myArray, 2) To UBound(myArray, 2)
MsgBox myArray(x, y)
Next y
Next x

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•