Access Global not working

918 views Asked by At

I have a Global Variable called EmployeeID. I set this by calling a function:

   Global EmployeeID As Integer
   Public Sub init_Globals(emp As Integer)
       EmployeeID = emp
    End Sub

On the main form, I used:

MsgBox EmployeeID

from a button and it works just fine; but the funny thing is when I use this from a subform it returns a 0: I might add that this is a Continuous Form as well.

Private Sub cboWhichDate_AfterUpdate()
    Me.txtEmployee = EmployeeID
End Sub
1

There are 1 answers

0
Mathieu Guindon On BEST ANSWER

A "global" variable can only be "global" if its scope is global. Sticking a Global access modifier to a field declared in a class module doesn't make it global.

In fact, the Global keyword is deprecated, and is completely replaced/superseded by the Public access modifier.

What matters is the variable's scope. If that declaration is located in a class module (a form's code-behind is essentially a class module), then all you've done is declare a public instance field; you can only access the value via the object instance that owns it.

Dim MyObject As New MyForm
MyObject.EmployeeID = 42

MsgBox MyObject.EmployeeID

To make a global variable, add a standard module (.bas) to your project, and declare it there.

Public EmployeeID As Integer

Now everyone everywhere can access EmployeeID, because it's scoped to a module (i.e. not an instance of an object), and its accessibility is public.

That said, global variables are evil and can easily lead to unmaintainable spaghetti code; Consider passing values as parameters instead.