Is it possible to declare a public variable in vba and assign a default value?

后端 未结 8 690
旧时难觅i
旧时难觅i 2020-12-09 01:33

I want to do this but it won\'t compile:

Public MyVariable as Integer = 123

What\'s the best way of achieving this?

8条回答
  •  暖寄归人
    2020-12-09 01:38

    As told above, To declare global accessible variables you can do it outside functions preceded with the public keyword.

    And, since the affectation is NOT PERMITTED outside the procedures, you can, for example, create a sub called InitGlobals that initializes your public variables, then you just call this subroutine at the beginning of your statements

    Here is an example of it:

    Public Coordinates(3) as Double
    Public Heat as double
    Public Weight as double
    
    Sub InitGlobals()
        Coordinates(1)=10.5
        Coordinates(2)=22.54
        Coordinates(3)=-100.5
        Heat=25.5
        Weight=70
    End Sub
    
    Sub MyWorkSGoesHere()
        Call InitGlobals
        'Now you can do your work using your global variables initialized as you wanted them to be.
    End Sub
    

提交回复
热议问题