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.
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
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.