SlowLearner
SlowLearner

Reputation: 3294

Multiple Listeners for VBA Custom Event

In VBA (for MS Word) is it possible to have multiple listeners for a custom Event? I created a custom event as per: Custom Event not firing but what I really want is to have multiple listeners...

It seems logical that an event only fires for the instance that it relates to, but I want to trigger code several places when an event occurs... is it possible?

Modified code form above Ref:

FactoryTest calls Factory. Factory raises an event. FactoryTest Listens for Event and responds.

Add a new class module and name it Factory

Public Event AfterInitialize()
Private Sub Class_Initialize()

End Sub

Public Sub test()
    RaiseEvent AfterInitialize
End Sub

Add another class module and name is FactoryTest

Private WithEvents cFactory As Factory

Private Sub Class_Initialize()
    Set cFactory = New Factory
    cFactory.test
End Sub

Private Sub cFactory_AfterInitialize()
    Debug.Print "after inialized..."
End Sub

And add a standard Module with the code below

 Sub Main()

    Dim fTest As FactoryTest
    Set fTest = New FactoryTest

End Sub

Upvotes: 1

Views: 611

Answers (1)

gembird
gembird

Reputation: 14053

Hope I understand your problem correctly. If you need that all the FactoryTests respond to single event you'll probably have to pass the reference to one common Factory to all the FactoryTests instances and not create new one in each FactoryTest. HTH

Standard module, here the common instance of Factory is created and two FactoryTests which both respond to the same event of Factory

Option Explicit

 Sub Main()
    Dim myFactory As Factory
    Set myFactory = New Factory

    Dim test1 As FactoryTest1
    Dim test2 As FactoryTest2

    Set test1 = New FactoryTest1
    Set test2 = New FactoryTest2

    Set test1.FactoryInstance = myFactory
    Set test2.FactoryInstance = myFactory

    myFactory.test
End Sub

Factory test class module, create more of them where each receives reference to one common Factory instance

Option Explicit

Private WithEvents cFactory As Factory

Private Sub cFactory_AfterInitialize()
    Debug.Print "after inialized..." & VBA.TypeName(Me)
End Sub

Public Property Get FactoryInstance() As Factory
    Set FactoryInstance = cFactory
End Property

Public Property Set FactoryInstance(ByRef factoryObject As Factory)
    Set cFactory = factoryObject
End Property

Output for two Factory test classes named FactoryTest1 and FactoryTest2

after inialized...FactoryTest1
after inialized...FactoryTest2

Upvotes: 1

Related Questions