Question

When To Use Custom Events

Asked by: shacho

I 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(LineText as String), which drops the line into a textbox and inserts a carriage return.  Why would this make more sense than just having a public FileText Property in the class or a GetText Procedure?

Mike

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-03-17 at 22:48:42ID24240528
Tags

VBA Custom Events

Topics

Microsoft Excel Spreadsheet Software

,

Microsoft Access Database

,

Outlook Groupware Software

Participating Experts
4
Points
500
Comments
21

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

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.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

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.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

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.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Withevents
    If I skip the Event RenameNode row I get the error message Object does not source Automation events. Why is this row necessary? ==form code (a form with a treeview) Option Explicit Dim WithEvents urban As nisse Private Sub Form_Load() Set urban = New nisse urban....
  2. WithEvents and MsAccess
    When you use WithEvents, you usually refer to a very specific object. In a form, you refer to a TextBox or Combox or.. where the event occurs on (Public withevents mtxtbox as textbox). I am trying to refer to raise an event on any control on a form whatever is the control ty...
  3. WithEvents in VBA
    I have implemented connection points in a COM object and would like to capture the events through a VBA client. Please advice if VBA supports WithEvents and if so cna you please provide ane xample. Thanks,
  4. WithEvent in VB.net
    Can someone give me a simple and basic of what Withevent does? I am very new to VB.net and I only have a background in DbaseIII+ programming and a bit of VBA. I appreciate your help. thanks

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

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.

Join the Community

Answers

 

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

 

by: hnasrPosted on 2009-03-18 at 00:35:43ID: 23916250

Look at access example by searching help: look for raiseevent

Try this model!
Change l, and w values and check!

 

by: NatchiketPosted on 2009-03-18 at 02:14:53ID: 23916645

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 :)

 

by: roryaPosted on 2009-03-18 at 02:30:18ID: 23916714

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

 

by: hnasrPosted on 2009-03-18 at 02:46:17ID: 23916790

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.

 

by: shachoPosted on 2009-04-12 at 17:58:07ID: 24127523

Thanks everyone for your comments.
hnasr - not sure I follow your example.  What action should raise this event and what is the event handler meant to do?

Mike


 

by: chris_bottomleyPosted on 2009-04-12 at 23:27:58ID: 24128200

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

 

by: chris_bottomleyPosted on 2009-04-12 at 23:29:02ID: 24128201

Shaco / Hnasr ... both have 5 characters, sorry each

Chris

 

by: hnasrPosted on 2009-04-13 at 05:51:08ID: 24129382

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_AllowedAreaExceeded(ByVal a As Single)
    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).

 

by: shachoPosted on 2009-04-13 at 18:18:11ID: 24134304

Hnasr,

Thanks for the lengthy explanation.  Unfortunately, and I apologize for this, what I
meant was, I don't understand your child (age), adult (age), senior(age) example.
Can you explain how this would work?  No code is necessary - just an explanation
of how it would work and why it is useful.

Mike

 

by: hnasrPosted on 2009-04-14 at 04:35:27ID: 24136974

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."

 

by: shachoPosted on 2009-04-16 at 22:22:00ID: 24165072

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

 

by: hnasrPosted on 2009-04-17 at 08:33:42ID: 24168853

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!

 

by: shachoPosted on 2009-04-23 at 17:09:29ID: 24220875

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

 

by: chris_bottomleyPosted on 2009-04-23 at 23:07:02ID: 24222101

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

 

by: shachoPosted on 2009-05-10 at 18:15:43ID: 24350896

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

 

by: chris_bottomleyPosted on 2009-05-10 at 21:57:25ID: 24351553

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

 

by: hnasrPosted on 2009-05-10 at 23:17:20ID: 24351888

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.

 

by: chris_bottomleyPosted on 2009-06-15 at 11:20:53ID: 24631441

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

 

by: shachoPosted on 2009-06-16 at 22:36:04ID: 24645088

Noted.  Thanks all for your comments.

Mike

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...