Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an Array from a Range in VBA

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.

like image 838
basaltanglia Avatar asked Jun 07 '16 21:06

basaltanglia


People also ask

How do I create an array of a range in VBA?

Steps to Add a Range into an Array in VBA First, you need to declare a dynamic array using the variant data type. Next, you need to declare one more variable to store the count of the cells from the range and use that counter for the loop as well. After that, assign the range where you have value to the array.


1 Answers

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.

like image 172
vacip Avatar answered Oct 11 '22 12:10

vacip