为什么我们不能将范围中的值分配到静态数组中:
Sub test()
'error occours
Dim a(1 to 10) as Double
'also don't work :
'Dim a(1 To 10, t To 1) as Double
a = Range("A1:A10")
End Sub
答案 0 :(得分:1)
因为已经分配了数组,无论您使用多少维度。
Dim x(1 to 10, 1 to 1) As Variant '// You've allocated the array
x = Range("A1:A10").Value '// Can't allocate to an already allocated array
您可以声明类型Variant
的数组而不分配它,而是使用它:
Dim x() As Variant '// Array is NOT allocated
x = Range("A1:A10") '// x = Array sized 1 to 10, 1 to 1
以这种方式直接为数组分配范围将始终返回类型Variant/Variant
,因此接收数组也必须是Variant
类型。
您可以创建一个UDF来为您执行此操作,但它有点无法直接从范围分配:
Sub SO()
Dim a As Variant
a = RangeToArray(Range("A1:A10"))
End Sub
Function RangeToArray(rng As Range) As Variant
ReDim x(1 To rng.Rows.count, 1 To rng.Columns.count) As Variant
Dim r As Long, c As Long
For r = 1 To rng.Rows.count
For c = 1 To rng.Columns.count
x(r, c) = rng.Cells(r, c)
Next c
Next r
RangeToArray = x
End Function