variables

C

Chris

If I hav a variable that I use 50 times in a program ' stDocname ' for
example.

Am I better to Dim the variable in a module, sub procedure or just put it in
the private procedure every time I want to open a fom?
 
K

Klatuu

It depends on the useage. It is always best to scope a variable as tightly
as possible. It this case, I suspect that stDocname is unique to each
procedure and should be dimmed in each procedure. You should only Dim a
variable at a module level if multiple procedures need to use the same value.
Global varialbes have their use, but should be avoided where possible.
 
C

Chris

So say for instance stDocname = name of a form.

If in the module I type
Dim stDocname as string

Then at a local level I type stDocname = frmEdit
this is wrong because the stDocname will be different for every procedure.

However, If I have intYear in the module this is ok because all the
procedures that are using intyear are accessing the same value
Dim intyear as Integer (module)

intyear = me.cboYear (Entering the DB the user will select the years records
he wants to view and all the forms will be filtered by the same value)

Am I on the right lines?
 
K

Klatuu

Yes, you are on the right track. Your example of strDocname is dead on.
Your example of intYear is correct assuming different forms within the app
will be using it. Since I personnaly have an aversion to Global variables, I
have a little trick for capturing and returning values that are needed in
multiple places in the application. The reason I do it this way is because
queries cannot understand VBA variables, but they can understand User Defined
Functions, so in my case, I have to run some queries that need to know the
year, but the form where the year was captured has closed. Here is a Static
Function:

Static Function GetClosingYear(Optional varYear As Variant) As Long
Dim lngClosingYear As Long

If Not IsMissing(varYear) Then
lngClosingYear = CLng(varYear)
End If
GetClosingYear = lngClosingYear
End Function

To set the value
lngGone = GetClosingYear(Me.txtCurrYear)
To get the value
lngGone = GetClosingYear()
To use it in a query
GetClosingYear()

A Static Function will retain all its variable values as long as your app is
running if you put them in a standard module. The enstantiation of the
variables follows the same rules as enstantiating any variable. So, what
this code does is if you pass it no value, it returns whatever the current
value is. If you pass it a value, it assignes the variable lngClosingYear
the value that was passed and returns that value.

Using this method, you can access the captured value anywhere in the
applcation. Using a Global varialbe, it is not available to queries and, of
course, you run the risk, if you don't use good naming conventions, of
duplicating the variable name and creating problems.
 
Top