Creating an Array from a Range in VBA

Issue

I’m having a seemingly basic problem but can’t find any resources addressing it.

Simply put, I just want to load the contents of a Range of cells (all one column) into an Array.

I am able to accomplish this by means of

DirArray = Array(Range("A1"), Range("A2"))

But for some reason, I cannot create the array when expressed this way:

DirArray = Array(Range("A1:A2"))

My real Range is much longer (and may vary in length), so I don’t want to have to individually enumerate the cells this way. Can anyone tell me how to properly load a whole Range into an Array?

With the latter code:

MsgBox UBound(DirArray, 1)

And

MsgBox UBound(DirArray)

Return 0, whereas with the former they return 1.

Solution

Just define the variable as a variant, and make them equal:

Dim DirArray As Variant
DirArray = Range("a1:a5").Value

No need for the Array command.

Answered By – vacip

Answer Checked By – Pedro (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.