Coding event handling in a class

M

mscertified

I'm trying to figure out how to declare and raise events in a class and how
to trap those events in the code that uses the class.
I'm refering to both Access books and VB6 books.
I coded "Public Event Status(ByVal StatusText as string)" in my class module
and the syntax checker rejected it. I got this code directly from a VB6 book.
Does anyone have sample code that declares and raises events in a class
module?

David
 
B

Brendan Reynolds

In a custom class module ...

Option Compare Database
Option Explicit

Private m_TestProp As String

Public Event PropChanged(ByVal OldVal As String, ByVal NewVal As String)

Public Property Let TestProp(NewVal As String)

Dim OldVal As String
OldVal = m_TestProp
m_TestProp = NewVal
RaiseEvent PropChanged(OldVal, NewVal)

End Property

Public Property Get TestProp() As String
TestProp = m_TestProp
End Property

Private Sub Class_Initialize()
m_TestProp = "Initial Value"
End Sub

In a form module ...

Option Compare Database
Option Explicit

Private WithEvents TestObj As clsTest

Private Sub Command0_Click()
TestObj.TestProp = Me.Text1
End Sub

Private Sub Form_Open(Cancel As Integer)
Set TestObj = New clsTest
End Sub

Private Sub TestObj_PropChanged(ByVal OldVal As String, ByVal NewVal As
String)
MsgBox "Property changed from " & OldVal & " to " & NewVal
End Sub

Note that VBA is picky about where you put your declarations - make sure the
event declaration ("Public Event PropChanged(ByVal OldVal As String, ByVal
NewVal As String)" in this example) goes in the Declarations section at the
top of the class module, before any properties or methods.
 

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