Forum Discussion

bvelke's avatar
bvelke
Brass Contributor
Jun 12, 2019
Solved

Public array

I'm confused about how to declare a public array.  I originally (before I realized that I'll need to reference it elsewhere) had it declared in a Sub in Module4 as follows:

Sub MyTest()
Dim Horse(5) As String
   Horse(1) = "BE"
   Horse(2) = "BI"
   Horse(3) = "BL"
   Horse(4) = "BU"
   Horse(5) = "CA"
End Sub

I tried this which I understood from what I read here and elsewhere would make it available from any other Sub in the same module:

Public Horse(5) as String

But that produces a compile error "Invalid attribute in Sub or function."

I tried declaring the Sub public but that didn't help:

Public Sub MyTest()

I tried putting the declaration in the Workbook_Activate() method but that produces a Type Mismatch error when the array is referenced elsewhere.

I've been reading many threads on the subject of declaring public arrays and I think that I'm following their advice.  But I'm obviously missing something and my head is starting to hurt.

Thanks for any help.

PS: Is that how I should format code in a post (above)?

  • bvelkehere is a good explanation of scope 
    https://stackoverflow.com/questions/2722146/how-do-i-declare-a-global-variable-in-vba

     

3 Replies

  • EricBrady's avatar
    EricBrady
    Copper Contributor

    bvelke  try declaring the variable outside of the sub..

    public Horse(5) as string

     

    Sub myTest()

          Horse(1)="BE"

     

    end Sub

     

    • bvelke's avatar
      bvelke
      Brass Contributor

      EricBrady Thanks but that produces a compile error, "Invalid outside procedure."

      • EricBrady's avatar
        EricBrady
        Copper Contributor

        bvelkehere is a good explanation of scope 
        https://stackoverflow.com/questions/2722146/how-do-i-declare-a-global-variable-in-vba

         

Resources