Help defining a public variable

E

Edo2008

I've read in several Access 2007 books that I can have a CLASS MODULE
(not one bound to a form or report) define public variables,
subroutines and functions. So I defined a public varable, a public
SetID subroutine and a public GetID function. This is all in Class1.

From a form, if I call SetID (2), I get "Sub or Function not defined".
From a form, if I call Class1.SetID (2), I get "Runtime Error 424.
Object Required".

Can someone tell me how to store just one global variable I can set
from one form and access from another (even if the first form is
closed)?
Thanks
-Ed



This is Class1

Option Compare Database
Option Explicit

Public gIntPatientID As Integer 'Currently Selected Patient
Public Sub SetID (intID As Integer)
gIntPatientID = intID
End Sub

Public Function GetPatientID()
GetPatientID = gIntPatientID
End Function
 
M

Marshall Barton

Edo2008 said:
I've read in several Access 2007 books that I can have a CLASS MODULE
(not one bound to a form or report) define public variables,
subroutines and functions. So I defined a public varable, a public
SetID subroutine and a public GetID function. This is all in Class1.

From a form, if I call SetID (2), I get "Sub or Function not defined".
From a form, if I call Class1.SetID (2), I get "Runtime Error 424.
Object Required".

Can someone tell me how to store just one global variable I can set
from one form and access from another (even if the first form is
closed)?


This is Class1

Option Compare Database
Option Explicit

Public gIntPatientID As Integer 'Currently Selected Patient
Public Sub SetID (intID As Integer)
gIntPatientID = intID
End Sub

Public Function GetPatientID()
GetPatientID = gIntPatientID
End Function


That code is how you would do it in a STANDARD module.
However, your example should use a private variable so other
modules can not modify the variable without using your sub
procedure.

While you can create Function and Sub procedures in a class
module and use them as methods of the class, your example
should use Property Let and Property Get statements (see VBS
Help for details):

Private mID As Integer

Public Property Let ID(intID As Integer)
mID = intID
End Property

Public Property Get ID()
ID = mID
End Property

This way the code to use the class would be more like:

Dim Patient As clsPatient 'Class1 is not a good name
. . .
Set Patient As New clsPatient
. . .
Patient.ID = 2
. . .
x = Patient.ID
 

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