1

Is there a way to declare a public variable and also assign value?

This is the code in a sub which works perfectly:

Option Explicit

Sub test()


    Dim arrStatistics As Variant

    'Set arrStatistics
    arrStatistics = Array("H/T - Goal Scored", "H/T - Goal Conceded", "H/T - Both teams Scored", "H/T - Over 0.5", "H/T - Over 1.5", "H/T - Over 2.5", "H/T - Result" _
                , "F/T - Goal Scored", "F/T - Goal Conceded", "F/T - Both teams Scored", "F/T - Over 0.5", "F/T - Over 1.5", "F/T - Over 2.5", "F/T - Result")

End Sub

This is how a declare the variable to act as Public:

Public arrStatistics As Variant

BUT when i use this i receive an error:

Public arrStatistics As Variant

'Set arrStatistics
arrStatistics = Array("H/T - Goal Scored", "H/T - Goal Conceded", "H/T - Both teams Scored", "H/T - Over 0.5", "H/T - Over 1.5", "H/T - Over 2.5", "H/T - Result" _
                , "F/T - Goal Scored", "F/T - Goal Conceded", "F/T - Both teams Scored", "F/T - Over 0.5", "F/T - Over 1.5", "F/T - Over 2.5", "F/T - Result")
1
  • For a non-array value that doesn't change (i.e. it is constantly the same value ), you can also use a Const, like so: Public Const SomeText As String = "This is a Constant!". But, to reiterate, this won't work with an Array. Commented Sep 12, 2019 at 11:47

1 Answer 1

4

No, you must declare your variable public outside the procedure

Option Explicit

Public arrStatistics As Variant

And then initialize the content with a procedure.

Public Sub InitPublicVariabels()

    arrStatistics = Array("H/T - Goal Scored", "H/T - Goal Conceded", "H/T - Both teams Scored", "H/T - Over 0.5", "H/T - Over 1.5", "H/T - Over 2.5", "H/T - Result" _
            , "F/T - Goal Scored", "F/T - Goal Conceded", "F/T - Both teams Scored", "F/T - Over 0.5", "F/T - Over 1.5", "F/T - Over 2.5", "F/T - Result")

End Sub

But instead of having large data in the code it might be an option to put the data into a hidden worksheet, that you can read into the array easily. Much more convenient to edit the data, and a good practice to seperate code and data.

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

Comments

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.