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

oiopk7p5  于 2022-12-24  发布在  其他
关注(0)|答案(3)|浏览(265)

我有一段代码可以填充数组

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

在这里,您可以看到监 windows 口中的值是中加载的值

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

是否可以将整个数组粘贴到工作表中,而不必循环遍历数组?
在看了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
xj3cbfub

xj3cbfub1#

正如我在上面的评论中提到的,你不需要一个数组来执行你想要做的操作,但是如果你只想要一个数组的解决方案,那么你不需要走很长的路来填充一个循环中的数组。直接将范围的值赋给数组。它将创建一个二维数组,你不需要转置。

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
jgwigjjp

jgwigjjp2#

您将需要使用transpose worksheet function
如下所示。您必须将其分配给范围值:

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
ar7v8xwq

ar7v8xwq3#

只是将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

相关问题