Creating Custom Class Events

You can, of course, create your own events. Once you've decided on the specific events you want to expose, you declare them in the class's declarations section. Let's say we have a class that implements an animal purchase. You may want to provide events that notify your code before and after a purchase has been made.

Public Event BeforePurchase(Cancel As Integer) Public Event AfterPurchase() Public Event AmountInvalid()

Events are declared Public by default, but we always explicitly declare them for clarity. In any case, nothing outside the class would ever know about an event that was declared Private. Event names can be alphanumeric, but must begin with a nonnumeric character, and they can only be raised in the module that declared them.

To fire an event in your class, you issue the RaiseEvent command. For example, the following code demonstrates a typical use:

Public Sub Purchase_Dog(curAmount As Currency) If curAmount > 0 Then

RaiseEvent Before_Purchase(Cancel As Integer)


RaiseEvent Amount_Invalid() End If End Sub

Just like VBA procedures, you can declare event arguments using the ByVal and ByRef keywords. By default, event arguments are passed ByRef, which means that the code that's listening for the event can change its value, and that change is passed back to the class procedure.

0 0

Post a comment