Database development and training for Birmingham and the midlands
Specialists in Microsoft Access and Visual Foxpro database training and development
I am happy to hear from existing clients but I am taking no new calls.
Methods in a class module
The new class module comes with two methods:
- runs when an object is created from this class.
- runs when the object is destroyed.
Both of these are private Subs because nothing outside the class has any need to use them. In this example there's nothing that needs to be done in either of these methods. We need to add a Public Sub so that we can call it from the rest of the system.
Adding the Warn method
This method will display a dialog box showing our message. It will show the warning icon and have the name of our app as its caption.
'-- Displays a warning messagebox
MsgBox strMessage, vbExclamation, "Sample Database"
Using the Warn method
The first thing to do is to create a MessageBox object from the class. This only has to be done once. A class like this will be used throughout the database so declare it as Public and set it up as the application is loading.
'-- Public because it's used everywhere.
Public MessageBox As clsMessageBox
'-- Create the messagebox handler
Set MessageBox = New clsMessageBox
Now that the MessageBox object exists we can just call it any time that we want to display a warning dialog:
This has been a trivial example but still useful. If you extend the MessageBox class to include methods named Info and Stop then your code will be easier to write and easier to read. Even after twenty years, a call to MsgBox "Record deleted", 48, "My Application Name" still leaves me in doubt as to whether 48 is the code for Information or Warning or Stop. The meaning of a call to MessageBox.Warn "Record deleted" is obvious.
I find that a fourth method named Confirm is the most useful method in my version of this class because it makes it easier for me to get an answer from the user. The standard messagebox returns 1, 2, 6, or 7 depending on whether you're using OK/Cancel or Yes/No buttons. My version returns True/False so the code always reads:
There is less scope for me to make silly typos and the dialogs all have a consistent style. If the client wants to change from Yes/No to OK/Cancel then I just change the one method in MessageHandler.
To go back to an earlier way of working, this function shows how I did the same thing some years ago with a VBA function.