Home » excel » How to populate array from a sheet column in Excel

How to populate array from a sheet column in Excel

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have an array like this :

myColumns = Array("Serial","Practice","Manager", "QTD")

But I want to fetch its values from a sheet to make it more dynamic. (The values & their number may vary)

enter image description here

So I tried this to affect the range from A2 to last value of the column to my array:

myColumns = Range(Range("A2"), Range("A2").End(xlDown)).Value

It results in :

UBound(myColumns) -> 4 -> OK

BUT when I do this :

s = myColumns(3) -> Subscribe out of range ! 

How is that possible?

How can I populate it correctly?
Thank you!

How to&Answers:

Application.Transpose is a good friend of yours, if you are parsing a single column:

Sub TestMe1()
    Dim myArr As Variant
    myArr = Application.Transpose(Range("A1:A10"))

    Dim cnt As Long
    For cnt = LBound(myArr) To UBound(myArr)
        Debug.Print myArr(cnt)
    Next cnt

End Sub

enter image description here


If you are parsing a single row, you should transpose twice:

Sub TestMe2()
    Dim myArr As Variant
    With Application
        myArr = .Transpose(.Transpose(Range("A1:AI1")))
    End With
End Sub

enter image description here


If you are simply parsing multiple range or without .Transpose(), you have to refer to both columns and rows:

enter image description here