PDA

View Full Version : Access public form variable losing value after event ends?



Wadelf
07-15-2017, 03:56 PM
MS Office 365, MS Access, VBA
I know I can use a Module public (global) variable, but it would seem that I should (and maybe have in past versions) be able to use a public variable declared on top of the form code that would retain it's value between events?

I set it's value in an event, then right after, in another event, the value is gone? If I call another procedure, function, class module, etc. from an event the value is maintained, but after the event ends the value is gone?

I am very old school when in the late 80s programs would have a memory leak and keep using memory, so I feel that a Module global variable would use memory/performance/etc when I should be able to declare a variable within a form and it will keep it's value while the form is open even between events, as a public (global) module variable does throughout the application while the app is open. A public (global) module variable works. I thought I once did this years ago?

SamT
07-15-2017, 04:56 PM
Personally, I would use a Private Module level variable in the Form's module. I don't know if that would make a difference in your situation, but it would prevent any other code from accessing the variable. I would also prefix the variable name with an "f"

Private fVarName as whatever

If the problem persists, I would try converting it to a Property

Private fVarName As Whatever

Private Property Get PropertyName() As Whatever
PropertyName = fVarName
End Property

Private Property Let PropertyName(InputValue As Whatever)
fVarName = InputValue
End Property

Note that if the Variable is an Object type, You need to use a Property Set sub. If you declare the Property Subs Public, any code in any module can access them

How to use in UserForm event codes

Sub CommandButton1_Click()
Me.PropertName = "SeventySeven Bottles Of Beer"
End Sub

Sub CommandButton2_Click()
With Me
.Label1.Caption = .PropertyName
.PropertyName = ""
End With
End Sub

If you declare the Properties Public, then in another module, (While the Form is NOT unloaded,)

Sub T()
Dim MyVar As STring
MyVar = UserForm1.PropertyName
UserForm1.PropertyName = "A Partridge in a Pear tree"
End Sub