Trying to learn custom event handling for class modules.

J

JGPatrick

I'm trying to learn how to use custom events with class modules. I create a
class module called clsGreeter and place the following code in it:

********
Public Event Greet()

Public Sub Handshake()

RaiseEvent Greet

End Sub
*******

To make the Handshake method actually do something, I create another class
module called clsEnglishGreeter and insert the following code:

*********
Private WithEvents grtng As clsGreeter

Public Property Set Greeting(grtr As clsGreeter)

Set grtng = grtr

End Property

Private Sub grtng_Greet()

MsgBox ("hello")

End Sub

***********

Then to use the class module clsEnglishGreeter, I enter the following code
into an ordinary module:


***********
Sub GreetVisitors()

Dim eg As clsEnglishGreeter

Set eg.Greeting = New clsGreeter

eg.Greeting.Handshake

Set eg.Greeting = Nothing

Set eg = Nothing

End Sub
**************

eg.Greeting should be an instance of the clsGreeter object, so I should be
able to invoke the Handshake method. And by the way the Greet event procedure
is defined for eg.Greeting, when I invoke the Handshake method, I should get
a message box that says hello.

Instead, I get an error message on the line

Set eg.Greeting = New clsGreeter.

The error is object or with block variable not set.

I would be grateful if someone would explain why I get that error.
 
D

David W. Fenton

before using eg you have to initialize it:

set eg = new clsEnglishGreeter
Set eg.Greeting = New clsGreeter

If you don't mind having the instances automatically initialize
themselves, you can declare their variables with the New keyword:

Dim EnglishGreeter As New clsEnglishGreeter

That will automatically initialize itself the first time you use it
in code.

Sometimes this is helpful, sometimes it is not.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top