0

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)

2
  • 2
    d = d + Array(a) ? What are you trying to do? It is very difficult to tell what you are trying to do, and what you expect to happen. Commented May 3, 2014 at 2:07
  • Sorry, this is just test code with extra stuff in it. I am trying to get 3 copies of a() into d as an array of objects. I tried that line and it doesn't work. I edited the code to more concisely show what I am trying to do. Commented May 3, 2014 at 3:33

1 Answer 1

2

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
2
  • I tried this and I'm getting an error. Please see my edits of the op Commented May 4, 2014 at 0:21
  • Why did you not follow the example I gave you? d(i) = Array(a) creates an Array of Arrays of Arrays. With your code, you would need to write x = d(1)(0) to access the inner most array. Examine your varibles in the watch window to see what I mean. Commented May 4, 2014 at 4:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.