Search notes:

VBA statement: raiseEvent

The raiseEvent statement invokes the procedures that had been assigned as handlers for the raise event.

sender.cls

option explicit

'
'  Declare the name of a message …
'
public event message(text as string)

public sub sendMessage(text as string) ' {
  '
  ' Send the specified message text
  '
    raiseEvent message(text)
end sub ' }
Github repository about-VBA, path: /language/statements/raiseEvent/simple-example/sender.cls

receiver.cls

option explicit


  '
  ' This class wants to receive messages that
  ' were sent by an instance of the sender class.
  ' The following declaration specifies (a reference)
  ' to the instance which will send the messages:
  '
private withEvents snd as sender

private            id  as string


public sub init(snd_ as sender, id_ as string) ' {
  '
  ' We need to assign the reference to our member
  ' variable snd in order to connect messages
  ' that were sent from the instance to our
  ' member function snd_message (below)

    set snd = snd_
        id  = id_

end sub ' }

private sub snd_message(text as string) ' {
  '
  '  This is the method that receives the events that were
  '  sent with raiseEvent(message).
  '
  '  The method name consists of two parts that are separated by
  '  an underscore. The first part corresponds to the name of the
  '  member variable that was declared with »withEvents« (snd), the
  '  second part is the name of the event that we have an interest in.
  '
     debug.print id & " received " & text
end sub ' }
Github repository about-VBA, path: /language/statements/raiseEvent/simple-example/receiver.cls

test.bas

option explicit

sub main ' {

  '
  ' Create two instances that will send messages
  ' messages:

    dim snd_1 as new sender
    dim snd_2 as new sender

  '
  ' Create three receivers
  '
    dim rcv_1 as new receiver
    dim rcv_2 as new receiver
    dim rcv_3 as new receiver

  '
  ' Assign the senders to the receivers:
  '
    rcv_1.init snd_1, "foo"
    rcv_2.init snd_2, "bar"
    rcv_3.init snd_1, "baz"

  '
  ' Send the messages
  '
    snd_1.sendMessage "Message one"
    snd_2.sendMessage "Message two"

end sub ' }
Github repository about-VBA, path: /language/statements/raiseEvent/simple-example/test.bas

See also

VBA statements

Index