MessageBox class

Methods in a class module

The new class module comes with two methods:

  • Initialise runs when an object is created from this class.
  • Terminate runs when the object is destroyed.
As with methods for a form, you can use the two combo boxes at the top of the screen to open either of these. Select Class from the lefthand box and then Initialise and Terminate will be the only two choices in the righthand box.

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.

Public Sub Warn(strMessage As String)
   '-- Displays a warning messagebox
   MsgBox strMessage, vbExclamation, "Sample Database"
End Sub

Using the Warn method

MessageBox dialog 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.

'-- This is the messagebox handler.
'-- 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:

MessageBox.Warn "This is a warning."

Summary

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:

If MessageBox.Confirm("Are you sure?") Then
  ...

rather than

If MsgBox("Are you sure?", 36, "Sample Database") = 6 Then
  ...

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.