RaiseEvent Problem

P

ps

In my study of RaiseEvent, I have a Question.
I have 2 Textboxes in UserForm1: TextBox1, TextBox2
When I run, Event is fired only on TextBox2.

TextBox1 does not fire Event.
What is the problem??

my codes...

---(Class1 module)-----
Private WithEvents mTx As MSForms.TextBox
Public Event F1Pressed()

Public Property Set Control(ByRef Ctl As MSForms.TextBox)
Set mTx = Ctl
End Property

Private Sub mTx_KeyDown( _
ByVal KeyCode As MSForms.ReturnInteger, _
ByVal Shift As Integer)

If Shift Then Exit Sub
RaiseEvent F1Pressed
End Sub

--(UserForm1 module)---------
Private Col As VBA.Collection
Private WithEvents myCls As Class1


Private Sub UserForm_Initialize()
Dim Ctl As Control

Set Col = New VBA.Collection

For Each Ctl In Controls
If TypeOf Ctl Is MSForms.TextBox Then
Set myCls = New Class1
Set myCls.Control = Ctl
Col.Add myCls
End If
Next

End Sub

Private Sub myCls_F1Pressed()
MsgBox "F1 Clicked"
End Sub
 
R

Rob Bovey

The problem is that inside your UserForm you are only trapping the
events of a single instance of your class. This declaration:

Private WithEvents myCls As Class1

was used over and over in a loop in the UserForm_Initialize event to assign
each textbox to an instance of your custom class and then add each instance
of that class to a collection.

The only reason this works at all is that at the end of the
UserForm_Initialize loop the myCls variable is left assigned to whatever the
last class you created was. If you have two textboxes on your UserForm this
will be TextBox2. Add more textboxes and it will be whatever one is last in
the initialize loop.

The method you are using here allows you to *trap* events and respond to
them using multiple instances of a single class module. However, once you
start raising custom events from inside a class module, you must have a
separate object variable for each instance of the class whose custom events
you want to respond to in some other class, in this case your UserForm
module.

There's no way to create a single event procedure in your UserForm to
respond to all the events for all your custom class instances. You'll need
to declare one WithEvents Class1 variable for each textbox on your UserForm
and create an F1Pressed event procedure for each.

--
Rob Bovey, Excel MVP
Application Professionals
http://www.appspro.com/

* Take your Excel development skills to the next level.
* Professional Excel Development
http://www.appspro.com/Books/Books.htm
 

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