[AccessD] Public Variables - Scope and Lifetime

Arthur Fuller artful at rogers.com
Sat Nov 26 15:46:24 CST 2005


Your reply made me decide to test static functions against a STOP, which I
have never done before.
Turns out that static values are preserved despite a STOP. Code follows. 
Place this in a new module:
<code>
Static Function CurrentValue(Optional lngNew As Long) As Long

    Dim lngCurrent As Long
    On Error GoTo CurrentValue_Error

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

    On Error GoTo 0
    Exit Function

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

End Function</code>
Place this in a new module:
<code>
Option Compare Database
Option Explicit

Sub TestPersistence()
    CurrentValue (123)
    MsgBox "Current value is: " & CurrentValue(), vbInformation + vbOKOnly,
"Test Persistence of Static Values"
    Stop
    MsgBox "Current value is: " & CurrentValue()
End Sub
</code>
Compile, then run the sub above. At the STOP, hit F5 to continue. The moral
of the story is that if you want values to persist beyond a STOP, use static
functions.
Arthur
-----Original Message-----
From: accessd-bounces at databaseadvisors.com
[mailto:accessd-bounces at databaseadvisors.com] On Behalf Of DWUTKA at marlow.com
Sent: November 26, 2005 1:42 PM
To: accessd at databaseadvisors.com
Subject: Re: [AccessD] Public Variables - Scope and Lifetime

Ugh....not this again!  LOL.  Marty, that is not what happens.  If you STOP
your code, then everything gets reset.  That does include your global
variables.  It's not a maybe, and they don't 'lose' their values, the code
is stopped.  It is just like stopping an .exe, all values in memory are
cleared.  The difference is, with Access, that the Access Shell didn't stop,
and as soon as you do something requiring code, Access starts it all up
again, and so your Globals will be reset.
It's not a wishy washy thing, it is just how the code works.
Drew




More information about the AccessD mailing list