在Excel VBA中添加到Array函数

时间:2014-05-03 02:03:03

标签: arrays excel vba excel-vba

我试图在for循环中将数组添加到Double数组的数组中。这是我的代码:

Sub Test3()
 Dim a() As Double, i As Integer
 ReDim a(1 To 10, 1 To 3)

 Dim d

 For i = 1 To 3
  d = Array(a)
 Next i

End Sub

在这个测试中,我只想在'd'中添加3个'a'副本。我有d = Array(a)当然不起作用,但我不知道用

替换它的行

为清晰起见编辑了代码

新代码尝试:

Sub Test3()
 Dim a() As Double, i As Integer
 ReDim a(1 To 10, 1 To 3)
 a(1, 2) = 3.5

 Dim d() As Variant

 For i = 1 To 3
  ReDim Preserve d(1 To i)
  d(i) = Array(a)
 Next i


 Dim x() As Double
 x = d(1)   ' Error, Type Mismatch

 MsgBox (x(1, 2))

End Sub

我在x = d(1)

上得到类型不匹配的错误

1 个答案:

答案 0 :(得分:2)

你想要的是什么称为" Jagged Array"或阵列数组

试试这个

Sub Demo()
    Dim a() As Double, b() As Double, c() As Double, i As Integer

    ReDim a(1 To 10, 1 To 3)
    ReDim b(1 To 2, 1 To 4)
    ReDim c(1 To 5, 1 To 11)

    a(1, 2) = 3.5
    b(1, 2) = 2.5

    Dim d As Variant
    ReDim d(1 To 6)

    ' Add 3 copies of a to d
    For i = 1 To 3
     d(i) = a
    Next i

    ' add other arrays to d
    d(4) = b
    d(5) = c

    ' Access elements of d
    Dim x() As Double
    x = d(1)

    MsgBox x(1, 2)
    MsgBox d(1)(1, 2)
    MsgBox d(4)(1, 2)
End Sub