[AccessD] Public Variables - Scope and Lifetime

Arthur Fuller artful at rogers.com
Sat Nov 26 09:06:52 CST 2005


You could also try the static function approach. For simple things like
preservation of a variable, I tend to prefer this over a class declaration,
but I don't want to start a war on this subject.
A static function is also known as a get/set function, which means that you
can either set the value or obtain it. If you pass a value in, that sets it;
if you don't, that obtains it. For example:
<code>
'---------------------------------------------------------------------------
------------
' Procedure : CurrentX
' DateTime  : 04/09/2003 
' Author    : Arthur Fuller
' Purpose   :
'           : Copy this template each time you need a new set/get function
'           : Then Replace "X" with the name of your object, i.e.,"Employee"
'           : Replace all in current proc and you're done.
'---------------------------------------------------------------------------
------------
'
Static Function CurrentX(Optional lngNew As Long) As Long

    Dim lngCurrent As Long
    On Error GoTo CurrentTimeBilledID_Error

    If lngNew <> 0 Then lngCurrent = lngNew
    CurrentX = lngCurrent
    #If conDebug = 1 Then
        Debug.Print "Current X: ", CurrentX
    #End If

    On Error GoTo 0
    Exit Function

CurrentTimeBilledID_Error:
    MsgBox "Error " & Err.Number & " (" & Err.Description & ")" & vbCrLf & _
    "in procedure CurrentX of Module CurrentValues"

End Function</code>

Given this template, you call the function in two ways:
1. SET: CurrentX( 123 )
2. GET: CurrentX() 'returns 123
--------------------------------
Others do things in other ways. I often see apps that reference a specific
form's controls in their queries, record sources and report arguments. I
never do this. Instead I write a query such as:
SELECT * FROM Orders WHERE CustomerID = CurrentCustomerID()
Then I use that query in the report or form in question. The function
CurrentCustomerID() is a clone of the code above, with CustomerID
substituting for X.
Suppose I have a button on a Customer form that should display the current
orders for the selected Customer.
I create the query as above, then build the report on it.
In the OnCurrent event of said Customer form, I write:
	CurrentCustomerID( Me.CustomerID )
I do it this way so that any button that invokes any process (related form,
report, query, whatever) knows the value of CurrentCustomerID(). 
An additional benefit of this approach is that all these components do not
depend on some form being open and its values set. Instead I can go into the
debug window, for example, set the value of CurrentCustomerID() and then run
any query or report I want. This appeals to me.
HTH,
Arthur




More information about the AccessD mailing list