MS-Access / Getting Started

Event Statement

Use the Event statement in the Declarations section of a class module to declare an event that can be raised within the module. In another module, you can define an object variable using the WithEvents keyword, set the variable to an instance of this class module, and then code procedures that respond to the events declared and triggered within this class module.

Syntax

[Public] Event eventname ([<arguments>])

where <arguments> is

{[ByVal | ByRef] argumentname [As datatype]},...

Notes

An Event must be public, which makes the event available to all other procedures in all modules. If you want, you can include the Public keyword when coding this statement.

You should declare the data type of any arguments in the event's argument list. Note that the names of the variables passed by the triggering procedure can be different from the names of the variables known by this event. If you use the ByVal keyword to declare an argument, Visual Basic passes a copy of the argument to your event. Any change you make to a ByVal argument does not change the original variable in the triggering procedure. If you use the ByRef keyword, Visual Basic passes the actual memory address of the variable, allowing the event to change the variable's value in the triggering procedure. (If the argument passed by the triggering procedure is an expression, Visual Basic treats it as if you had declared it by using ByVal.) Visual Basic always passes arrays by reference (ByRef).

Example

To declare an event that can be triggered from other modules, enter the following in the class module MyClass:

Option Explicit
Public Event Signal(ByVal strMsg As String)

Public Sub RaiseSignal(ByVal strText As String)
    RaiseEvent Signal(strText)
End Sub

To respond to the event from another module, enter the following:

Option Explicit
Dim WithEvents objOtherClass As MyClass

Sub LoadClass ()
    Set objOtherClass = New MyClass
End Sub

Sub objOtherClass_Signal(ByVal strMsg As string)
    MsgBox "MyClass Signal event sent this " & _
	"message: " & strMsg
End Sub

To trigger the event in any other module, execute the following:

MyClass.RaiseSignal "Hello"
[Previous] [Contents] [Next]