Discussion Locked

MS Access Global Variable

0 helpful
3 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

Global Variables - How do I set them up & access the value on several forms

I thought using Global variables was going to be very simple however I am
not sure how to start.

Basically, I want to set a the value of a variable on one form, run areport
with the criteria form closed, then when I close the report have the option
to open another form that would display some criteria data on a form that
was closed a before the report ran.

Is there a way to store data on a form into a variable that can be used
later? I was trying to use a global variable but cannot seem to figure out
how to define one.

3 replies

by kees.valkenswaard

It would be possible to use a text box or a label as a variable. In the latter case, with a label WHY, one would use WHY.Caption. However, the form should be loaded in order to use that variable. It is possible to use these ?variables? in macros.
It is probably better to define a public variable in a VBA module and use that in your different locations.
At the top of the module put something like:
Public varTHIS as variant
The variable varTHIS can subsequently be used everywhere in VBA code.
Good Luck.

by ideafixer

I found this easier:

Actually, global variables are easy to use. Like everything else, you've just got to know the "trick".

The first thing to do is to set up a module in which you define the public variables, such as:

Public strName as string
Public lngCount as long
(and so on)

Save the module under any name you want ("MyModule"?).

When you open your database, the modules are automatically executed and whatever public variables you defined in the module(s) will be available throughout your application.

It's also helpful to include in the module some functions that help you get to the values in the variables. For example:

Function ThisCount() as Long
ThisCount=lngCount
End Function

This may initially seem to be redundant, but it is the method that makes it easy to include the values of public variables as part of queries. And of course if you want to be able to do more involved calculations based on values in public variables, the functions also enable you to do that.

One area I've found public variables to be very useful for is to store a user's ID and work group based on a login form I created for applications. I can then use the values of the ID, work group, and other related items, such as selected true/false variables for access to different functions in the application. It also provides me with the data to post where I want to record the ID of the user who made changes.

From: Bob Sellman

This discussion is closed to new replies.