0

I have a sub (initialisation) which contains several arrays. I am then creating another sub (testSub) which have to access one of the arrays in initialisation. I am unsure how to do this and would appreciate any help you can offer.

Initialisation sub:

Sub initialisation()

   init_array = Array("apple", "orange", "car")

   init_array_2 = Array("coconut", "keys", "blue")

End Sub

testSub:

Sub testSub()

For Each element in init_array 'Does not work currently
   [do stuff]
Next

End Sub
Pᴇʜ
  • 56,719
  • 10
  • 49
  • 73
ChartProblems
  • 415
  • 4
  • 16
  • 1
    You need to pass the array to the second sub either byRef or byValue `Sub testSub(init_array as Variant)`. – FAB Jun 13 '19 at 11:11
  • You coul declare your array as Public, so you can access from anywhere in your project. Check https://stackoverflow.com/a/51865287/9199828 and read the section **Dim vs Private vs Public** – Foxfire And Burns And Burns Jun 13 '19 at 11:16

2 Answers2

4

You need to pass it as parameter like this:

Option Explicit
Sub initialisation()

    Dim init_array As Variant, init_array_2 As Variant

    init_array = Array("apple", "orange", "car")
    init_array_2 = Array("coconut", "keys", "blue")
    testSub init_array

End Sub
Sub testSub(init_array As Variant)

    Dim element As Variant

    For Each element In init_array 'Does not work currently
       [do stuff]
    Next

End Sub

You should also use Option Explicit which will force you to declare all your variables.

Damian
  • 5,152
  • 1
  • 10
  • 21
2

You can also define your arrays outside subs:

Option Explicit

Dim init_array As Variant, init_array_2 As Variant

Sub initialisation()
    init_array = Array("apple", "orange", "car")
    init_array_2 = Array("coconut", "keys", "blue")
End Sub
Sub testSub()
Dim element As Variant
For Each element In init_array 'Does not work currently
   [do stuff]
Next

End Sub
Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
  • I have tried this solution along with declaring the sub as public but I still can't make this work. I get the same error that init_array is empty. – ChartProblems Jun 13 '19 at 11:30
  • Because you need to execute `initialisation` before `testSub` and do it in one `Sub`, otherwise you'll get an error – Michał Turczyn Jun 13 '19 at 11:31