将数组输出到范围的快速方法

时间:2019-03-04 13:24:59

标签: excel vba

如何将一个数组变量输出到以sheets(“ test”)。range(“ a1”)开始的范围内?是否有任何方法可以将数组输出到NamedRange而不先转储到单元格中?

有没有不循环的方法吗?

更新。数组中元素的数量不是恒定的,并且在刷新或用户输入时会更改。我的问题的重点是如何调整范围的大小,使其适合数组。

2 个答案:

答案 0 :(得分:2)

1-D 数组的简单示例

行数组:

Sub arrayTest()
    Dim arr(1 To 3) As String
    Dim r1 As Range
    Set r1 = Range("A1:C1")

    arr(1) = "larry"
    arr(2) = "moe"
    arr(3) = "curly"

    r1 = arr
End Sub

或数组到列:

Sub arrayTest2()
    Dim arr(1 To 3) As String
    Dim r1 As Range
    Set r1 = Range("A1:A3")

    arr(1) = "larry"
    arr(2) = "moe"
    arr(3) = "curly"

    r1 = Application.WorksheetFunction.Transpose(arr)
End Sub

2-D 数组同样容易:

Sub arrayTest3()
    Dim arr(1 To 3, 1 To 2) As String
    Dim r1 As Range
    Set r1 = Range("A1:B3")

    arr(1, 1) = "larry"
    arr(2, 1) = "moe"
    arr(3, 1) = "curly"
    arr(1, 2) = "gary"
    arr(2, 2) = "student"
    arr(3, 2) = "whatever"

    r1 = arr

End Sub

EDIT#1:

假设我们有一个任意的一维数组,从零开始或从一开始,我们想将其推入以单元格 B9 开始的行:

Sub arrayTest4()
    Dim r1 As Range, U As Long, L As Long, rBase As Range
    Set rBase = Range("B9")
    arr = Array("qwert", 1, 2, 3, 4, "ytrew", "mjiop", "nhy789")

    L = LBound(arr)
    U = UBound(arr)
    Set r1 = rBase.Resize(1, U - L + 1)

    r1 = arr

End Sub

enter image description here

答案 1 :(得分:0)

在此,我根据加里(Gary)的学生答案构建了两个有用的摘要。谢谢加里的学生!

Sub Array2DToRange()
    Dim Arr()
    ReDim Arr(0 To 2, 0 To 0) 'handles also Arr(1 to 3, 1 to 1)
    Arr(0, 0) = "Spinosaur"
    Arr(1, 0) = "T-Rex"
    Arr(2, 0) = "Triceratops"

    Dim R As Long, C As Long
    R = UBound(Arr, 1) - LBound(Arr, 1) + 1
    C = UBound(Arr, 2) - LBound(Arr, 2) + 1

    Range("k1").Resize(R, C).Value = Arr
End Sub

Sub Array1DToRange()
    Dim Arr()
    ReDim Arr(0 To 2) 'handles also Arr(1 to 3)
    Arr(0) = "Spinosaur"
    Arr(1) = "T-Rex"
    Arr(2) = "Triceratops"

    [a1].Resize(UBound(Arr) - LBound(Arr) + 1, 1) = Application.Transpose(Arr)
End Sub