如何粘贴整个数组而不在VBA中循环它?

时间:2013-10-10 15:50:55

标签: arrays excel vba excel-vba

我有这个代码将填充数组

Sub rangearray()

    Dim arr() As Variant
    Dim Rng As Range
    Dim myCell As Range
    Dim i As Integer

    Set Rng = ActiveSheet.Range("G10:G14")

    For Each myCell In Rng
        ReDim Preserve arr(i)
        arr(i) = myCell
        i = i + 1
    Next myCell

    ActiveSheet.Range("H10:H14") = arr()

End Sub

在这里,您可以看到监视窗口中的值是

中加载的值

enter image description here

除此之外,当我将数组添加回工作簿时,它只会粘贴数组的第一个元素。

enter image description here

是否可以将整个数组粘贴到工作表而无需遍历数组?

在看了一下Sorceri的链接后,我修改了代码以使用.Transpose函数,所以我修改后的代码现在看起来像这样:

Sub rangearray()

    Dim arr() As Variant
    Dim Rng As Range
    Dim myCell As Range
    Dim i As Integer

    Set Rng = ActiveSheet.Range("A1:A5")

    For Each myCell In Rng
        ReDim Preserve arr(i)
        arr(i) = myCell
        i = i + 1
    Next myCell

    ActiveSheet.Range("B1:B5") = WorksheetFunction.Transpose(arr)

End Sub

3 个答案:

答案 0 :(得分:9)

您需要使用转置工作表函数http://msdn.microsoft.com/en-us/library/office/ff196261.aspx

见下文。您必须将其分配给范围的值

Sub rangearray()

Dim arr() As Variant
Dim Rng As Range
Dim myCell As Range
Dim i As Integer

Set Rng = ActiveSheet.Range("A1:A5")

For Each myCell In Rng
    ReDim Preserve arr(i)
    arr(i) = myCell
    i = i + 1
Next myCell

ActiveSheet.Range("B1:B5").Value = WorksheetFunction.Transpose(arr)

End Sub

答案 1 :(得分:8)

正如我在上面的评论中提到的那样,您不需要一个数组来执行您尝试执行的操作,但如果您只需要一个数组解决方案,那么您不需要花很长时间来填充数组在一个循环中。直接将范围的值分配给数组。它将创建一个您不需要转置的2D数组。

Sub rangearray()
    Dim arr
    Dim Rng As Range

    With ActiveSheet
        Set Rng = ActiveSheet.Range("G10:G14")

        arr = Rng.Value

        .Range("H10").Resize(UBound(arr, 1)).Value = arr
    End With
End Sub

答案 2 :(得分:0)

只需将Rng分配给arr,然后放回工作表即可。它在Excel 2016中对我有效

Sub rangearray()

    Dim arr() As Variant
    Dim Rng As Range
    Dim myCell As Range
    Dim i As Integer

    Set Rng = ActiveSheet.Range("A1:A5")

    arr = Rng

    ActiveSheet.Range("B1:B5").Resize(5) = arr

End Sub