The Answer submitted by @Storax is the basis for the following code, which defines function rangeToArray
that will take a Range
object and return an equivalent array
:
Function rangeToArray(rg As Range)
If rg.Count = 1 Then
rangeToArray = Array(rg(1))
Else
rangeToArray = WorksheetFunction.Transpose(rg)
End If
End Function
It can be used like so:
Sub test()
Dim lastRowInA As Long, i As Integer
Dim a()
lastRowInA = WorksheetFunction.CountA(Range("A:A"))
a = rangeToArray(Range("A1:A" & lastRowInA))
For i = 1 To lastRowInA
Debug.Print a(i)
Next
End Sub
The if
inside rangeToArray
is necessary only if rg
could consist of a single cell.
Also, if A
has no populated rows, an error will result when using lastRowInA
, which will be 0
, to define the range being passed torangeToArray
.
The single line from Storax, shown below and adapted in the Else
in function rangeToArray
, is a brilliant, simple key to solution.
vDat = WorksheetFunction.Transpose((rg))