R3PooC
R3PooC

Reputation: 21

VBA Multi dimensional Arrays used in multiple subs

Ok so I am still trying to work out Arrays, I am learning quickly but still have one specific area I cannot get round which is frustrating.

I am trying to reference an array across multiple subs and when clicking a button, I am populating the array with strings and integers (which works fine).

The array is Publically declared.

How do I get the multi array to work across the different subs? I have tried using paramArray myArray as variant but I'm doing something wrong and respectfully requesting help here.

Please don't get caught up in the detail of my code below (its probably wrong), the way im adding the data here and what the data is isn't the question, its about how im using the array.

Thanks

Public myArray()

Sub Main()
redim preserve myArray(10,5)
for z = 0 to 10
  for y = 0 to 5
     myArray(z,y) = 10 * Z + y
  Next y
Next z
End Sub

Sub Butn_Click()
  MsgBox myArray(0,1)
End sub

Sub testcode()
  MsgBox myArray(2,1)
end sub

Upvotes: 0

Views: 658

Answers (2)

R3PooC
R3PooC

Reputation: 21

I just tried amending the code so it flowed to see if I can replicate the problem I was having... but it does work, typical!

Thank you for your responses!

Public myArray()

Sub Main()
    UserForm1.Show
End Sub

Sub testcode()
  MsgBox myArray(2, 1)
End Sub

Sub testcode2()
    MsgBox myArray(0, 1)
    unload userform1
End Sub

The below code is in the userform code to ensure the button click works...

Sub Butn_Click()

  ReDim Preserve myArray(10, 5)
    For Z = 0 To 10
      For y = 0 To 5
         myArray(Z, y) = 10 * Z + y
      Next y
    Next Z

    Call testcode
    Call testcode2
End Sub

Upvotes: 0

Gary's Student
Gary's Student

Reputation: 96753

With:

Public myArray()

Sub Main()
    ReDim Preserve myArray(10, 5)
    For Z = 0 To 10
      For y = 0 To 5
         myArray(Z, y) = 10 * Z + y
      Next y
    Next Z
End Sub

Sub Butn_Click()
  MsgBox myArray(0, 1)
End Sub

Sub testcode()
  MsgBox myArray(2, 1)
End Sub

First call Main() then call Butn_Click() then call testcode()

All appear to work.

Upvotes: 1

Related Questions