I am trying to write an array to a range and I have tried several ways but no matter what, I always get only the FIRST value of the array over and over again.
Here i
Do this:
arrayData = Array("A", "B", "C", "D", "E")
[a1].Resize(UBound(arrayData) + 1) = Application.Transpose(arrayData)
The important bit is the Transpose() function.
But it is better to work with 2D arrays from the get go if you plan on writing them to the worksheet. As long as you define them as rows in the first rank and columns in the second, then no transposition is required.
This:
Sub test()
ActiveWorkbook.Worksheets("Sheet1").Cells.Clear
Dim arrayData(1 To 5, 1 To 1) As Variant
arrayData(1, 1) = "A"
arrayData(2, 1) = "B"
arrayData(3, 1) = "C"
arrayData(4, 1) = "D"
arrayData(5, 1) = "E"
Dim rngTarget As Range
Set rngTarget = ActiveWorkbook.Worksheets("Sheet1").Range("A1:A5")
rngTarget = arrayData
End Sub
will produce:
If I may expand the accepted answer, I propose:
[a1].Resize(UBound(arrayData) - LBound(arrayData) + 1) = Application.Transpose(arrayData)
That would be the safe way. This will work no matter if you declare your array variable as:
Dim arrayData(0 to 2)
or
Dim arrayData(1 to 3)
The accepted answer works only in the second case.
The proposed way might be useful if the size of array is unknown and you declare your arrayData as:
Dim arrayData()