• 0

redim preserve variant type


Question

Is there a trick to resizing variant type variables? 

 

I have a pretty simple code

Sub Button1_Click()
Dim y As Variant
y = Range(Cells(1, 1), Cells(2, 4)).Value

ReDim Preserve y(UBound(y, 1), UBound(y, 2) + 1) As Variant

Range(Cells(3, 1), Cells(4, 5)).Value = y

End Sub

the ReDim bit throws an out of scope error. I have to use variant since range.value returns a variant type. 

 

can you think of a way to fix this? I am reading http://msdn.microsoft.com/en-us/library/office/gg251578.aspx and it says.

 

"To resize an array contained in a Variant, you must explicitly declare the Variant variable before attempting to resize its array."

 

I don't know what that means... 

Link to comment
Share on other sites

2 answers to this question

Recommended Posts

  • 0

Taken from the exact page you linked in your post:

 

'Similarly, when you use Preserve, you can change the size of the array only by changing the upper bound; changing the lower bound causes an error.'

 

When you're using your redim you're only trying to set the lower bound use this instead:

ReDim Preserve y(1 To UBound(y, 1), 1 To UBound(y, 2) + 1) As Variant

Alternatively you could use (for when your lowest value isn't 1):

ReDim Preserve y(LBound(y) To UBound(y), LBound(y,2) To UBound(y, 2) + 1) As Variant
Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.