Igor Rivin
Igor Rivin

Reputation: 4864

VBA globals declarations

This is a really naive question, I am guessing. I have some global variables

Dim foo, bar as Double

Which are then set to something:

Sub setter()
   foo = 3.14
   bar = 2.718
End Sub

I want the variables to be initialized on startup, which, I gather can be done with

 Private Sub Auto_open()
     Call setter
 End Sub

The question is: will this pick up the declarations, or is there some other magic I need to do?

Upvotes: 0

Views: 229

Answers (2)

Mathieu Guindon
Mathieu Guindon

Reputation: 71187

Dim can't be used to declare globals. Use Dim for declaring local variables inside a procedure scope.

When used at module level, Dim is equivalent to Private, and you should use Private instead, for consistency (Private antagonizes Public much more clearly than Dim does).

Dim foo, bar as Double

Note that this makes bar a Double, and leaves foo an implicit Variant. If both are intended to be Double, then the declaration should look like this:

Dim foo As Double, bar As Double

I would recommend declaring one single variable per statement.

Dim foo As Double
Dim bar As Double

Much easier to maintain that way.

As for your question, assuming everything is in the same module, you're fine - and the variables don't need to be global (Public - there's a Global keyword too, but you can only use it in a standard module, and it's functionally identical to Public, so don't use Global, it's obsolete), since no other module needs to access them.

Note that it's very, very, very rare that you need global variables. Most of the time, you'll be passing parameters between procedures instead.

Upvotes: 1

HackSlash
HackSlash

Reputation: 5803

Use Properties instead. That is what they are for. This gives you a globally readable property that can only be set locally by the initializer.

EXAMPLE:

Option Explicit

Private localFoo As Double

Private Property Let foo(fooval As Double)
    localFoo = fooval
End Property

Public Property Get foo() As Double
    foo = localFoo
End Property

Private Sub Auto_open()
    initFoo
End Sub

Private Sub initFoo()
    foo 3.14
End Sub

SOURCE: https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/property-set-statement

Upvotes: 1

Related Questions