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
2
  • 1
    You need to pass the array to the second sub either byRef or byValue Sub testSub(init_array as Variant). Commented Jun 13, 2019 at 11:11
  • You coul declare your array as Public, so you can access from anywhere in your project. Check stackoverflow.com/a/51865287/9199828 and read the section Dim vs Private vs Public Commented Jun 13, 2019 at 11:16

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

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.
Because you need to execute initialisation before testSub and do it in one Sub, otherwise you'll get an error

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.