繁体   English   中英

在Excel VBA中添加到Array函数

[英]Adding to an Array function in 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)时得到类型不匹配的错误

你想要的是所谓的“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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM