Global variables

  • Thread starter Thread starter H. Martins
  • Start date Start date
H

H. Martins

I suppose I can declare Global variables so that they can be accessed
as soon as an Access project is opened.

I suppose that once declared all forms will be able to access them.

I suppose they must be declared immediately after Option Compare
Database.

I can't find out in which module they must be placed. Is there a
special one? Must some sort of #include be used in the other modules
(forms)?.

Thanks
H. Martins
 
I believe you will find that all of the standard modules are loaded before
any of your forms so that any global variables or public functions are
available to the forms. No #INCLUDE necessary.
 
Access modules are loaded into memory as any procedure within one is called.
If you call a Global variable from a form, it will initialize. One of the
drawbacks to using Globals though is that should there be an error, they
will often uninitialze and you will be left hanging without a warning. For
that reason, it is wise to either:

1. Not use Global variables.
2. Supply them with a default value.
or
3. Fill them with a function that will re-initialize them as necessary.
 
Standard modules are not opened until something in the module is referenced.
Once open, the stay open for the session.

First rule of Global variables -- Don't use them.
One problem is when an unhandeled error occurs, the values in Global
variables are cleared.

It is better to design your app so that all variables are scoped to the form
or report level at most. In cases where it becomes absolutely necessary, a
better technique is to use a Public function in a standard module with a
static variable. This gets past the error problem. The idea is that when
the function receives a value, it stores it in the static variable. Then it
returns whatever the current value of the static variable is. Here is an
example:

Public Function SomeVar(Optional varNewValue As Variant) As String
Static varOldValue As Variant

If Not IsMissing(varNewValue) Then
varOldValue = varNewValue
End if
SomeVar = varOldValue
End Function

The function type can be whatever data type you want it to be. So can
OldValue.
The function argument must be a Variant.
 
Back
Top