为什么我的数组的第一项被分配给范围内的所有单元格?
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
答案 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
唯一需要注意的是,如果有超过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