I'm attempting to read a list of cell values in to an Array in Excel VBA. I am doing this through:
Dim varHrArray As Variant
varHrArray = Range(Cells(TITLE + 1, HR_LOCATION), Cells(TITLE + intHrLength, HR_LOCATION)).Value
While this works, it's creating a 2d array and I am uncertain exactly why. This has been confirmed by by message boxes, with MsgBox (varHrArray(1, 1))
working as expected but MsgBox (varHrArray(1))
giving a 'Subscript Out Of Range' error and through directly examining the variable in the watch window - varHrArray
is showing as Variant/Variant(1 to 7, 1 to 1)
(7 is correct for the length of the list, by the way).
I'm not clear why this is happening or how it can be stopped.
Whenever an array is created using range of cells then array created will always be a two dimensional array. This is because a spreadsheet stores values in two dimensions i.e. rows and columns. So the first dimension is the rows and the second dimension is the columns.
Moreover, lower bound of array will always be 1 i.e. LBound(varHrArray)=1.
You can loop through the array as
Though there are methods to convert 2-d array into 1-d array. One of them being
Above is part of this article.
Application.Transpose
is a great way of passing a single column or row range into a 1d variant array. For example:Note that your range is transposed by this function. This means a column range becomes a 1d row variant array, and vica versa, so you might want to transpose it again before you return it to the worksheet:
... or alternatively, transpose it twice at the start: