Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One-dimensional array from Excel Range

Tags:

I'm presently populating my array Securities with the following code:

Option Base 1 Securities = Array(Worksheets(3).Range("A8:A" & SymbolCount).Value) 

This produces a 2-dimensional array where every address is (1...1,1...N). I want a 1-dimensional array (1...N).

How can I either (a) populate Securities as a 1-dimensional array, or, (b) efficiently strip Securities to a 1-dimensional array (I'm stuck at a with each loop).

like image 948
Felix Avatar asked Oct 04 '11 13:10

Felix


People also ask

How do you convert a range to an array?

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.

How do I convert 1D array to 2D in Excel?

You're using Excel, so you can use the Transpose function from VBA. Transpose will automatically convert a 1D array to 2D array. I wanted exactly what the OP wanted, but transpose just converts a 1D row to a 2D column array with multiple rows and one column.

What is a one dimensional array in VBA?

The one-dimensional array consists of list of items of same data type. It consists of either single row or column data. We read values from an array or into an array using index value. The one dimensional array can be created in static array or dynamic array. An array can be resized with ReDim statement.


1 Answers

I know you already accepted an answer but here is simpler code for you:

If you are grabbing a singe row (with multiple columns) then use:

Securities = application.transpose(application.transpose _              (Worksheets(3).Range("A8:A" & SymbolCount).Value)) 

If you are grabbing a single column (with multiple rows) then use:

Securities = application.transpose(Worksheets(3).Range("A8:A" & SymbolCount).Value) 

So, basically you just transpose twice for rows and once for columns.

Update:

Large tables might not work for this solution (as noted in the comment below):

I used this solution in a large table, and I found that there is a limitation to this trick: Application.Transpose(Range("D6:D65541").Value) 'runs without error, but Application.Transpose(Range("D6:D65542").Value) 'run-time error 13 Type mismatch

Update 2:

Another problem you might have as mentioned in the comments:

If one exceeds 255 characters, the function fails.

It has been a long time since I worked with Excel VBA but this might be a general limitation of accessing the data this way?

like image 168
Jon49 Avatar answered Oct 15 '22 21:10

Jon49