13

我有这段代码将填充一个数组

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

在这里你可以看到监视窗口中的值是已经加载的

在此处输入图像描述

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

在此处输入图像描述

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

在查看了 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
4

3 回答 3

17

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

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
于 2013-10-10T16:26:48.090 回答
14

您将要使用转置工作表功能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
于 2013-10-10T15:54:44.893 回答
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
于 2019-01-25T20:21:33.003 回答