为什么我在向Range分配数组时遇到问题

时间:2016-04-01 16:42:35

标签: excel vba excel-vba

为什么我的数组的第一项被分配给范围内的所有单元格?

Private Sub sample()
    Dim arr() As Double, rng As Range, i As Double
    ReDim arr(1 To 100)
    For i = 1 To 100
        arr(i) = i * Rnd
    Next i

    Set rng = Range("A1:A100")
    rng.Value = arr
End Sub

根据Locals窗口,我的数组已按预期填充: enter image description here

但是当数组被分配到范围时,它会将第一个值分配给所有单元格: enter image description here

3 个答案:

答案 0 :(得分:3)

为了将数组赋值给一个范围,需要将数组声明为二维数组。即使第二维只有一个元素:

ReDim arr(1 To 100, 1 To 1)

工作示例如下所示:

Private Sub sample()
    Dim arr() As Double, rng As Range, i As Double
    ReDim arr(1 To 100, 1 To 1)
    For i = 1 To 100
        arr(i, 1) = i * Rnd
    Next i

    Set rng = Range("A1:A100")
    rng.Value = arr
End Sub

答案 1 :(得分:2)

数组是一个水平的1维数组,需要转换为垂直的1维数组:

Private Sub sample()
    Dim arr() As Double, rng As Range, i As Double
    ReDim arr(1 To 100)
    For i = 1 To 100
        arr(i) = i * Rnd
    Next i

    Set rng = Range("A1:A100")
    rng.Value = Application.Transpose(arr)
End Sub

enter image description here

唯一需要注意的是,如果有超过64,500个元素,则需要手动完成转置,并进行循环。

答案 2 :(得分:-2)

试试这个:

Sub sample()
    Dim arr() As Double, rng As Range, i As Double
    ReDim arr(1 To 100)
        Set rng = Range("A1:A100")
    For i = 1 To 100
        arr(i) = i * Rnd
        rng.Cells(i, 1).Value = arr(i)
    Next i


End Sub