<< Back to Classes index page
In our first simple example clsSimple, all the properties - OrderID and so forth - could be altered by a VBA program because they were declared as Public. If we want some of our properties to be read-only, we need to make the variable Private and use the Property Get statement.
- Create a new class clsReadOnly by using Insert > Class Module in the Modules tab.
- Enter the following code:
Option Compare Database Option Explicit Private mlOrderID As Long Property Get OrderID() As Long OrderID = mlOrderID End Property
- In the Debug Window try entering the following commands:
set oro = new clsReadOnly ? oro.orderid oro.orderid = 99
This time we can still get the value of the object's property, but we can't set the value by using a statement like oro.orderid = 99
Actually, this particular example isn't really much use, but we'll see in later lessons how this code can be used very effectively to protect important properties, such as the OrderID, from accidental changes.
The opposite to the Property Get statement is the Property Let statement. If you look up the help on class modules you'll see examples like this:
Option Compare Database Option Explicit Private mlOrderID As Long Property Get OrderID() As Long OrderID = mlOrderID End Property Property Let OrderID(ID As Long) mlOrderID = ID End Property
In fact, this is no different to having a public variable OrderID like we did in our first simple example. This way just takes up more code. However, there are cleverer things to do with the Property Let statement, such as limiting the values it could take.
A note on naming conventions
The prefix cls used to name the Class Modules in the Modules window is another convention. You can call your classes anything you like, but it really helps if you are organised from the start. Having all your own Class Modules starting with cls differentiates them from the standard Access classes.
The instances of objects defined in VBA code start with o (lower case letter O) as in oSim. Again, there are numerous conventions for this. It's a matter of personal preference.
Any comments, feedback, questions: please send us a message.
This page first published circa 2000. Last updated 11 June 2014