简体   繁体   中英

Adding to an Array function in Excel VBA

I am trying to add an array to an array of Double arrays in a for loop. Here is the code I have:

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

In this test I'm just trying to add 3 copies of 'a' into 'd'. I have d = Array(a) which of course doesn't work, but I don't know what line to replace it with

Edited code for clarity

New Code Attempt:

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

I get the error of a type mismatch on x = d(1)

You want what's called a "Jagged Array", or Array of Arrays

Try this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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