[AccessD] Global default class instance
John Colby
jwcolby at gmail.com
Fri Oct 28 03:43:14 CDT 2022
I learned something today. Microsoft Access (VBA) has the ability to have
a default class instance. What this means is that you do not have to
instantiate the class to use it
Under normal circumstances, in order to use a class you have to dimension a
variable to hold a class and then instantiate the class in order to use
it. A 'default class instance' means that Access creates an instance of
the class for you without going through all this.
As you may know, a class has hidden attributes.
-
In the menu bar, click create, then in the toolbar click Class Module
-
A class module will be created named Class1. Save that.
-
Open the Class1 in the editor
-
Click File / Export file
-
Navigate to the location where your database container is stored.
-
Click Save. A file with the name of the module and a .cls extension will
be created, in this case ‘Class1.cls’
-
Open that file in notepad.
At the top of the file you will see a header that looks similar to this:
VERSION 1.0 CLASS
BEGIN
MultiUse = -1 'True
END
Attribute VB_Name = “Class1”
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = False
Option Compare Database
Option Explicit
These attributes can be edited. Edit the VB_PredeclaredID = True.
Save the file.
In the VBA editor, click File, Import File. Select the file you just
edited and click Open
Add the following code to the class.
Public Function GiveMeATwo() As Integer
GiveMeATwo = 2
End Function
Save the class.
In the immediate window type
Debug.Print Class1.GiveMeATwo
And hit enter.
The method of the class should execute and you should see a 2 on the next
line. Notice we never instantiated Class1.
In my testing however, the Class_Initialize() sub never fires, so if you
use that to initialize things (my framework 'initializes' using that event
sink) then you need to either go ahead and use the dimension method or call
an Init() method of your own to perform this initialization.
At any rate, another tool in my toolbox. My framework sometimes uses
classes where there is only a single instance of the class, for example the
framework class itself. Using this new tool I can simply use the default
instance instead of dim / instantiate / reference.
I'm jazzed!
--
John W. Colby
Colby Consulting
More information about the AccessD
mailing list