当我试图将数组转储Dim A (1 To 3) As String
到单元格的垂直范围时A1:A3
,数组的第一个单元格会在所有范围内重复。
例如,假设 A(1) = "a" , A(2) = "b" , A(3) = "c"
结果a
在所有A1:A3
范围内。
代码是Range("A1:A3").Value = A
我究竟做错了什么?
谢谢!
Sub Tester()
Dim a(1 To 3)
a(1) = "a"
a(2) = "b"
a(3) = "c"
Range("A1:A3").Value = a 'all "a"
Range("A1:C1").Value = a 'works, because left-to-right is the default
Range("A1:A3").Value = Application.Transpose(a) 'works
End Sub
我通常的做法是将数组重新设置为与范围对象相同的维度
对于 Range "A1:A3" 是一个 3*1 二维数组
Sub testing()
Dim a()
' a(1 to rowCount, 1 to columnCount)
ReDim a(1 To 3, 1 To 1)
a(1, 1) = "A"
a(2, 1) = "B"
a(3, 1) = "C"
Range("A1:A3").Value = a
End Sub
此函数将一维数组转置为“垂直”二维数组,然后可以将其分配给Range.Value
. Application.Transpose
不适合大数组(我的 Excel 2013 x64 上的 14464 个单元格)。
Private Function array_as_2d(arr)
'Convert 1D array into 2D array
Dim tmp
tmp = Array()
lb = LBound(tmp)
ReDim tmp(LBound(arr) To UBound(arr), lb)
For i = LBound(arr) To UBound(arr)
tmp(i, lb) = arr(i)
Next i
array_as_2d = tmp
End Function
Sub test_assign()
Dim a(0 To 2)
a(0) = 7
a(1) = 8
a(2) = 9
Range("A1:A3") = array_as_2d(a)
Range("B1:B3") = array_as_2d(Array(1, 2, 3))
End Sub