global variable

S

Souris

I wanted to pass parameter to my query using VBA which works.

I declared mydb in my module as a global variable, but I am unable to access
mydb from my form.

I just wnated to know is it a good idea to declare db as global variable
since it can be accessed any where in the program and I do not need set db
every time I need it.


If it is, how should I declare a db as a global variable.
I put on top of the module, it seems it is global on the module not the
application,

Your information is great is great appreciated,
 
K

Klatuu

To be truely global, a variable needs to be declared in a standard module.
Now, let me warn you against using global variables. On first use, it has to
load the entire module into memory. Then global variables loose their value
if any unhandled errors occur. It is best to avoid using global variables.
 
B

Baz

Hi Souris,

I would say it's not a bad idea, but you need to be careful of it being set
to nothing whenever you encounter an error in your code. To make it visble
throughout, declare it as Public i.e.

Public mydb As DAO.Database
 
M

Marshall Barton

Souris said:
I wanted to pass parameter to my query using VBA which works.

I declared mydb in my module as a global variable, but I am unable to access
mydb from my form.

I just wnated to know is it a good idea to declare db as global variable
since it can be accessed any where in the program and I do not need set db
every time I need it.


If it is, how should I declare a db as a global variable.
I put on top of the module, it seems it is global on the module not the
application,


You have a slight (or major?) misperception. A global
(Public) VBA variable in a standard module (not a
form/report/class module) is only available in VBA
procedures. They are not available in form/report control
source expressions. queries, etc.

Two things that are available everywhere(?) in Access are
controls on an open form and Public VBA Functions.

If you stuff the value into a text box on a (hidden, always
open) form, then a query can use it via the syntax:
Forms![name of the form].[name of the text box]

A global variable can be used by creating a function in the
same module. E.g.

Public MyVar As ...
Public Function GetMyVar()
GetMyVar = MyVar
End Function

A query can get the value of the variable by using:
GetMyVar()
wherever you need the value of the variable.

Note that the use of global variables is disvouraged for
several reasons, not least is the fact that they are cleared
whenever your project encounters an unhandled error.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top