如何在Excel中插入数组?

时间:2019-01-09 21:07:13

标签: excel vba

我正在尝试在excel中插入一系列预定值。这是我的代码:

Sub arr()

Dim arr As Variant
Set arr = [1,2,3,4,5]

    With ActiveSheet

        .Range("B1").Value = arr

    End With

End Sub

我想做的是在单元格B1中,插入上面具有值1到5的数组。此外,如果我想垂直显示这些值,我将如何处理?

谢谢

GSC

2 个答案:

答案 0 :(得分:2)

您可以使用Join()将数组合并到单个单元格中。

Sub arr()

Dim arr() As Variant
Dim i As Long
arr = Array(1, 2, 3, 4, 5)

    With ActiveSheet
        .Range("B1").Value = Join(arr, ",")
        ' The loop below will start in C1, and add a single array value until it's exhausted.
        For i = LBound(arr) To UBound(arr)
            .Cells(i + 1, 3).Value = arr(i)
        Next i
    End With
End Sub

或者,对于“垂直”数组,将我的For i循环替换为:.Cells(1,3).resize(Ubound(arr)+1).Value = Application.Transpose(arr)(感谢@ScottCraner!)

Thanks to @AndyG for the Join() idea

答案 1 :(得分:0)

Array To Range

Sub ArrayToRange()

    Const cString  As String = "1,2,3,4,5"

    Dim arr As Variant
    Dim vnt As Variant
    Dim i As Integer
    Dim cCell As String

    ' Write list to 1D Array.
    arr = Split(cString, ",")

    'arr = Array(1, 2, 3, 4, 5)

  ' 1D Array - arr

    ' Write to "A1:A5".
    cCell = "A1"
    Range(cCell).Resize(UBound(arr) + 1) = Application.Transpose(arr)

    '' Write to "B1:F1", writes values as text.
    'cCell = "B1"
    'Range(cCell).Resize(, UBound(arr) + 1) = arr

    ' Write to "B1:F1".
    cCell = "B1"
    Range(cCell).Resize(, UBound(arr) + 1) _
            = Application.Transpose(Application.Transpose(arr))

  ' 2D Array - vnt

    ' Resize 2D Array.
    ReDim vnt(1 To UBound(arr) + 1, 1 To 1)

    ' Write from 1D to 2D array.
    For i = 0 To UBound(arr)
        vnt(i + 1, 1) = arr(i)
    Next

    ' Write to "H1:H5".
    cCell = "H1"
    Range(cCell).Resize(UBound(vnt)) = vnt

    ' Write to  "I1:M1".
    cCell = "I1"
    Range(cCell).Resize(, UBound(vnt)) = Application.Transpose(vnt)

End Sub