Writing an array to a range. Only getting first value of array

后端 未结 3 867
没有蜡笔的小新
没有蜡笔的小新 2020-12-28 19:05

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

相关标签:
3条回答
  • 2020-12-28 19:26

    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.

    0 讨论(0)
  • 2020-12-28 19:43

    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:

    0 讨论(0)
  • 2020-12-28 19:51

    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()
    
    0 讨论(0)
提交回复
热议问题