assign a range of cells to an array

kevin_floyd

New Member
Joined
Jun 18, 2002
Messages
26
Is there a way to assign a range of cells to an array in one line of code? I can do it in a for loop, but I am looking for something quicker and easier.
 

Excel Facts

Save Often
If you start asking yourself if now is a good time to save your Excel workbook, the answer is Yes
Yes, like this-

Code:
Sub AssignToArray()
Dim var() As Variant

var() = Range("A1:A10") ' Read it in

Range("B1:B10") = var() ' Write it back

End Sub
 
Upvote 0
:oops:
is there any way to cycle through the variant array once it is loaded? I get a subscript error when i try to pull var(i) in a for i = 1 to 10 loop.
 
Upvote 0
You get a 2-D array, so you need something like this-

Code:
Sub AssignToArray()
Dim var() As Variant
Dim i As Long

var() = Range("A1:A10") ' Read it in

For i = LBound(var()) To UBound(var())
    MsgBox var(i, 1)
Next i

End Sub

Note that if you have read in more than more than one column, you can use code similiar to this: -

Code:
Sub AssignToArray()
Dim var() As Variant
Dim i As Long
Dim x As Long

var() = Range("A1:C5") ' Read it in

For i = LBound(var(), 1) To UBound(var(), 1)
    For x = LBound(var(), 2) To UBound(var(), 2)
        MsgBox var(i, x) ' Reads across then down
    Next x
Next i

End Sub
 
Upvote 0

Forum statistics

Threads
1,217,075
Messages
6,134,422
Members
449,872
Latest member
Big Jake

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top