Look at access example by searching help: look for raiseevent
Try this model!
Change l, and w values and check!
Main Topics
Browse All TopicsI have been programming Office applications with VBA for several years now and have read many books on the subject. One thing I have never quite been able to grasp is when and why to use custom events. Events for application objects make sense because they can start code execution with parameters when the the application is not already executing code. But in order for custom events to fire, code has to be already executing as a result of some other trigger. So what is the purpose of doing the extra coding just to make something an event plus handler, instead of an ordinary subroutine that passes parameters around? In fact, it seems that if you do use events and handlers, you're actually making the call chain harder to follow in the code. For example, one book provided an example where a user form has a public WithEvents object variable that is used to instantiate a text file class. The text file class has an OpenFile routine that accesses the text file reads it line by line. Each time a line is read, the ReadLine event fires. The listener then shifts execution back to the user form to handle MyTextFile_ReadLine(LineTe
Mike
This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.
Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.
If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.
Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.
Access the answers to your technology questions today.
30-day free trial. Register in 60 seconds.
Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Try it out and discover for yourself.
30-day free trial. Register in 60 seconds.
Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.
The only time I use custom events is when I have an object with a process that I want to keep the user up to date with. I then use a progress event when returns the stage or iteration number when the event fires, this can be used to drive a progress bar (assuming the object is instantiated from a form). Obviously there are other alternatives e.g. using the progressmeter in the status bar but hey it's kinda fun :)
Mike,
For one thing, you can have multiple event sinks listening for the same event. Using events is therefore much easier than trying to remember to trigger every bit of code that needs to run in response to an event. Additionally, it is much easier to just change the code in one event handler than it is to try and locate every piece of code that might have triggered that event. Consider the Worksheet_Change event for example. Imagine if you had to remember to run additional code every time you wrote a value to the worksheet, rather than simply having one event listener that responds automatically!
Does that help?
Regards,
Rory
One more exmple:
If you have a method that processes dateofbirth.
In this method you may RaiseEvent child (age), adult (age), senior(age)
You can have 3 sub procedures to handle the three events.
the procedures signatures will be like
Private Sub objOfClass_Child ( ......
Private Sub objOfClass_Adult (......
Private Sub objOfClass_Senior (......
This way coding is simplified,
If rules change for age grouping, you need to change the relevant code in the class.
Otherwise the code of the event handlers, the three procedures, need to be modified.
Many people are using access without custom events, but they are there, just if you decide to use them.
Shaco defines a class rather than an event handler ... i.e. greatly simplified object oriented programming.
As such you call the methods from other code as/when it is not strictly an event handler ... though an event handler could itself call such methods.
Of course Shaco might provide a better description ... this is just in case.
Chris
This is a class definition from the uploaded database: Class
'-------------------------
Option Compare Database
Private l As Single
Private w As Single
Public Event AllowedAreaExceeded(ByVal area As Single)
Public Function calcArea(ByVal l As Single, ByVal w As Single)
Dim a As Single
a = l * w
If a > 100 Then
RaiseEvent AllowedAreaExceeded(a)
End If
calcArea = a
End Function
'-------------------------
This class has two members:
Public function calcArea
Public event AllowedAreaExceeded
When the function is executed, it calculates the area of a rectangle, then compares the result with 100, if greater then you want an event to happen . You achive this by issuing the command
RaiseEvent AllowedAreaExceeded(a)
It is raised, allowed to happen, when a>100
Compare it to a Command1_click event, which occurs when we click a button.
This is the code behind the form:
Option Compare Database
Private WithEvents myClass1 As Class1
Private Sub Command3_Click()
Dim a As Single
a = myClass1.calcArea(10, 11)
End Sub
Private Sub Form_Load()
Set myClass1 = New Class1
End Sub
Private Sub myClass1_AllowedAreaExceed
MsgBox ("Area " & a & " exceeds allowed")
End Sub
Here are some helping notes which I taught today for a Visual Basic class. Command1, Command2, and so on are the default names access gives for command buttons when newly created.
1) Access helps us to create event-driven applications
2) Event driven means the application is idle and is waiting for an event to drive it (let it work)
3) The form has few controls with many events (actions) like button clicked, textbox changed, form clicked, form changed size, and mouse is hovering over an image.
4) Of all these events we select the suitable ones, when happen, to drive the application (event driven application)
5) As an example we select the click event of a command button (Command1_Click)
6) We need a procedure which will execute when the event occurs: In access a procedure that starts like,
Private Sub Command1_Click (&..) will execute when Command1 control is clicked.
This procedure is called an event handler.
This procedure is a must to drive the application
Code has to be inserted in this procedure to do useful work.
One statement may be to call a sub procedure to calculate the average of 3 numbers
Another statement may assign the result of a function to a variable
7) Other procedures should be included to cater for the previous commands
8) Command1_Click is an event handler, and the other procedure is "I call it an order or command handler, it handles the order or the command to do something"
9) There are situations when you need your own event to occur, like the area exceeds 100 units square.
10) You declare this type of event in a Class, and it will occur (when you issue RaiseEvent statement) in the procedures when the area > 100.
11) Command buttons, textboxes, and other controls are defined by access as classes. When you click on a button icon and draw a button on a form, access creates an object of the class called Command1 as default. The class has events and occur when we click or hover or change size and so on)
12) When you select click event of a button and write code it will handle the click event.
13) For our defined event, we write the procedure using the name of the event to handle the event when it occurs (Raised).
No problem:
1st step: we declare a class with the members:
1 child (age) event
2 adult (age)
3 senior(age)
4 calcAge (...)
this procedure accepts the dateofbirth and calculates the age.
It checks the age an decides 3 stages
1 child: raiseevent child(age)
2 adult : raiseevent adult (age)
3 senior: raiseevent senior(age)
2nd step: we use the class by creating an object objOfClass with the following members
1 objOfClass_Child event it occurs when age was in a stage to raise child event
2 objOfClass_Adult event it occurs when age was in a stage to raise adult event
3 objOfClass_Senior event it occurs when age was in a stage to raise senior tevent
Having three events we create 3 sub procedures to handle these events.
Private Sub objOfClass_Child ( ......
Private Sub objOfClass_Adult (......
Private Sub objOfClass_Senior (......
finally: what is the advantage?
"This way coding is simplified,
If rules change for age grouping, you need to change the relevant code in the class.
Otherwise the code of the event handlers, the three procedures, need to be modified.
Many people are using access without custom events, but they are there, just if you decide to use them."
Hmm. So the class is something like "Person"? What is supposed to happen in the main code when, for example, a "Child" event occurs? I am having a hard time understanding the practical application of this class and it's events. Can you describe an application where a class like this could be used?
Mike
Yes, having a class Called Person with properties and events like a person is Child, Adult, or Senior. A function in this class accepts an age as years groups the person to proper age group.
To use the class we create an Object variable called Driver As Person.
Compare this with Dim myTextBox As TextBox
Cehck the attached database for the Class Person, and Object Driver.
Try for number of years 17, 33, 77
If you want to change age groups you change it in the class definition and the program works normally.
Practical use,
In each event you may ask for other info relevant to the age.
If you want to add another age group called Infant, all you have to to is add this to the class.
Add the relevant sub for Driver_Infant.
You have a structured program, where less mistakes can creep in.
Good luck!
OK, I see how your code works. But what sort of handling might you want to do if a "Child" event is raised, for example?
In other words...
Private Sub Driver_Child(ByVal age As Single)
MsgBox ("Event occured or raised is: " & "Child event You can do what you need here")
'What sort of event handling might you want to have here?
End Sub
I would expect in normal terms that this use of an event would come into play when for instance the child event is raised and if for example it was a credit application then the event would reject it accordingly. i.e. it is simply activities that relate to the specific condition and could as said be coded as a direct check on age and calling a sub. The advantage of an event in this circumstance is as for Object oriented code in that it hides all the functionality making the main code easier.
You observe that the process of following such code can be harder than a linear sequence BUT it is in my view easier since it seperates out specific functionality, and therefore you can deal with specific code branches in isolation. Like all code however you can create excessive structures that make it harder but that is poor design rather than the mechanism.
Chris
Maybe this is just beyond my ability to comprehend it yet. But one last try. If the purpose is to find out whether or not a credit applicant is old enough to apply, what is the advantage of having an event triggered by the interrogation of the person's age value? Why not just examine the age property and decided in the code there and then if they are old enough? When you say "separating out functionality", what do you mean by this? Sorry I'm having so much trouble with this.
Mike
First off recall that this use of class is from HNASR, I commented on the more classical use of classes for application level events.
However again to use my best efforts:
Consider a 'box', this box is called Person and everywhere I want to do something on some data for person I push the data into the box and out comes my answer. Everywhere I use person I do exactly the same but one day I need to modify person. I might add a new capability in which case it is not immediately critical but if I change an existing capability to for example to extend the valid range then in this use of a class I make the change in one location - Person. In classical coding I would have to change every use of a code block doing this moding.
Classical coding - calculation is distributed and repetitive
Subroutine based - coding calculation is centralised but related data operates independently
Event oriented - coding calculation is centralised with related data all contained and working together
CHris
In Visual Basic, two types of events:
1 automatically happening (raised) events.
When you click a button then, whether you like it or not, a Button.CLick event occurs.
In fact many events happened before clicking the button, like mouse Enter, hover, Exit of any control the mouse crossed on its way to the Button.
To handle any of these events, you have to write a procedure and add to it Handles Object.Event (Ex: Private Sub EvH (...) Handles Button1.Click)
2 not automatically raised events
These are created by the user
You need to specify the event (in automatically raised events this is defined in the Button class by Visual Basic),
You need to tell visual basic when the event happens (this is defined in automatic events by Visual Basic)
You need to specify the code to handle the event, and this you have to do it for both
Why use Custom event?
You develop a program and you want (See, you want) to record info about the use of the program. You want to check if a user changed the price of a merchandize. You add an event in the class, and why not in the code? chris_bottomley commented on this to localize changes in one place. I add that a class hides data from the user. In the class you specify when to raise the event, may be you want to raise the event if certain users do that. You don't want the users to know (Security measures). This is called Data Hiding in Object Oriented Programming.
In the code you only incorporate the Event Handler, which may save the info passed to it into database. As Visual Basic knows when click event occurred, you alone know when a salary raises event occurs.
If you want to change the conditions for raising the salary raises event, you only do that in one place, in the class. You may be referring to salary rise in many places of your program and you do not want to hunt for the code to modify.
Jeroen
Across the interchange most of the questions were directed to HNASR in regard to his posts so I would suggest that pending a response from Shacho, that HNASR's response at 24129382 is the strongest link in the response chain and worth keeping as it gives good coverage of this use of the class entity.
Chris
Business Accounts
Answer for Membership
by: chris_bottomleyPosted on 2009-03-17 at 23:57:59ID: 23916080
The logic for individual programmers will vary and may have perfectly practical reasons, (for example the code you refer to may simply have been a way of demonstrating the use of an event class) but the events classing for me come into play because not everything is detected by for example outlook:
Outlook will not do anything when a mail is placed into a folder yet with events the add activity to the folder can be detected and the added item processed in some way.
Therefore from my perspective:
1. WithEvents class does things the default events do not.
2. It is possible that others use the class to support harmonidsation of activities between applications, either functionally or by code re-use.
Chris