Question

VBA Excel Multiple/Simultaneous Event Handling

Asked by: osknows

I need some advice on how best to code event handling using VBA within MS Excel.

I have 1 workbook, with say 20 worksheets. Each worksheet is linked to a 3rd party app where the 3rd party app writes data to each worksheet between every 0.1 to 1 seconds which changes periodically, therefore, updates of each worksheet are not in any particular order or set timeframe. I need to run some code to perform calcs on this data and write back into the same worksheet after each update.

This is relatively easy with 1 worksheet as I could use a 'worksheet_change' event, however, with mutliple worksheets and events I'm unsure how to proceed.

I could use a 'Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)' event but have a few questions

1. How do I capture a new event but allow current code to complete (eg Application.Enableevents = False will miss any events that trigger until set to true again)
2. What happens if code takes longer to run than the period between event triggers? Eg do the events stack and run in order or will they get missed?
3. Is there a way to run simultaneous events to avoid slowdown or stacking?

Any advice on this is greatly appreciated

Thanks,
Os

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-10-22 at 15:54:36ID24836479
Topics

VB Objects

,

Visual Basic Programming

,

Microsoft Excel Spreadsheet Software

Participating Experts
2
Points
500
Comments
13

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. VBA/Excel Copying Worksheets from one Workbook to An…
    How do I copy an Excel worksheet from a workbook (name of workbook is known) to another workbook (name of workbook is unknown) in vba?
  2. Re Excel200 - Turn AUto Calc off for specific worksheets
    I have some VBA that feeds through data from an input sheet to a calculation worksheet and then feeds the results through to an output sheet. As I want to feed through 10k+ lines of data, one by one to the calc sheet - I needed to speed things up as there are other calc's go...
  3. calc one & only one of 3 sheets in workbook
    Is there a way for me to calc one or two sheets in a three sheet workbook. The third sheet takes a very long time to calc but I don't need it nearly as often as the info on the other sheets. The other sheets have very little on them and no info needed from the third sheet to ...
  4. Create a column that lists all worksheets in the workbook th…
    Create a column that lists all worksheets in the workbook that start with "Calc" via VBA.
  5. VBA - Execute when worksheet deleted
    Here is what I need to happen. When any worksheet in the workbook that ends in with *_Calc is deleted, I want the value in Worksheets("UserEntry").[B2] cleared.
  6. VBA - count worksheets like *_Calc
    I can't believe how fast I forget to code this stuff after not using it for a month, anyway. Here is what I need, If the count of worksheets like *_Calc in this workbook is >0 then run some code.

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: aikimarkPosted on 2009-10-23 at 05:29:35ID: 25643692

If you have a multi-core processor, you might run an external process to check/scan for the updates and then do the calculations.  If you want to streamline the process, then the workbook_worksheetchange() event might set some lightweight semaphore for the external process to check.

Does the 3rd party app have some notification or hook mechanism?

Is there some timestamp on each sheet of the last 3rd party app update?

 

by: experts1Posted on 2009-10-23 at 07:05:44ID: 25644551

osknows,

My example below use the "Workbook_SheetChange()" subroutine to call specific subroutine for
each individual worksheet which triggers the SheetChange event.

The "Workbook_SheetChange()" subroutine will run whenever any sheet within the active workbook
is changed.

Be sure to use the "DoEvents" function within subroutines with loops (for, while etc..)
See example Sub "subroutine_to_process_sheet1()" which uses DoEvents.

My example is simple but the detailed possibilities can get quite complex.

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
 Dim sheet_name As String
 sheet_name = Sh.Name
  Select Case sheet_name = "sheet1"
     'call a subroutine to process sheet1
    Case sheet_name = "sheet2"
    'call a subroutine to process sheet2
    Case sheet_name = "sheet3"
    'call a subroutine to process sheet3
    Case sheet_name = "sheet4"
    'call a subroutine to process sheet4
    Case Else
    'Nothing to do
  End Select
End Sub
Private Sub subroutine_to_process_sheet1()
  For i = 1 to 1000000
    'Do something here
    DoEvents  'Allow other events to be handled and other subs to run
  Next i
End Sub
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:

Select allOpen in new window

 

by: experts1Posted on 2009-10-23 at 07:25:39ID: 25644736

osknows,

Sorry about syntax error for Select Case code above!  
:-)

Please see corrected syntax in code snippet below.

Regards,

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
 Dim sheet_name As String
 sheet_name = Sh.Name
  Select Case sheet_name
    Case "sheet1"
    'call a subroutine to process sheet1
    Case "sheet2"
    'call a subroutine to process sheet2
    Case "sheet3"
    'call a subroutine to process sheet3
    Case "sheet4"
    'call a subroutine to process sheet4
    Case Else
    'Nothing to do
  End Select
End Sub
 
Private Sub subroutine_to_process_sheet1()
  For i = 1 to 1000000
    'Do something here
    DoEvents  'Allow other events to be handled and other subs to run
  Next i
End Sub
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:

Select allOpen in new window

 

by: aikimarkPosted on 2009-10-23 at 07:37:29ID: 25644817

Since this is a real time application, code should be optimized.  Using the experts1 code as an example and my (async) external process idea, I would recommend the following changes:
1. remove the local string variable
2. use the Index property of the sheet in the Select Case structure.

Note: Integer comparisons are MUCH faster than string comparisons.

Example in snippet:

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
  Select Case Sh.Index 
    Case 1
      'signal external process for sheet1
    Case 2
      'signal external process for sheet2
    Case 3
      'signal external process for sheet3
    Case 4
      'signal external process for sheet4
  End Select
End Sub
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:

Select allOpen in new window

 

by: osknowsPosted on 2009-10-23 at 08:16:11ID: 25645223


Thanks for feedback so far, the code I have tried below will potentially pose some problems with what I'm trying to do. For example if I

1. Make a change in sheet1
2. Make a change in sheet2
3. Make a change in sheet3

I get the messagebox in order of 3,2,1. It appears each new event which triggers interupts the routine and runs before early events. Due to the number of potential events I may have the first event code may never complete

Is there a way to force the first event code to run to completion before moving onto the next event?

Thanks,
Os

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
 
  Select Case Sh.Index
    Case 1
     'call a subroutine to process sheet1
     subroutine_to_process_sheet1 (Sh.Index)
    Case 2
    'call a subroutine to process sheet2
    subroutine_to_process_sheet1 (Sh.Index)
    Case 3
    'call a subroutine to process sheet3
    subroutine_to_process_sheet1 (Sh.Index)
    Case 4
    'call a subroutine to process sheet4
    subroutine_to_process_sheet1 (Sh.Index)
    Case Else
    
    
    'call a subroutine to process all other sheets
    subroutine_to_process_sheet1 (Sh.Index)
  End Select
End Sub
 
Private Sub subroutine_to_process_sheet1(val As Integer)
For i = 1 To 100000
    DoEvents
Next i
 
  MsgBox (val)
  
End Sub
 
Private Sub subroutine_to_process_sheet2(val As Integer)
For i = 1 To 100000
    DoEvents
Next i
 
  MsgBox (val)
  
End Sub

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:

Select allOpen in new window

 

by: aikimarkPosted on 2009-10-23 at 08:55:43ID: 25645651

The problem is in your DoEvents placement.  When you call the routine from the Worksheet_Change event, the routine's DoEvent statement cedes control of code execution to the windows message processor before the routine has finished processing.  The next Worksheet_Change event is started, pushing the prior event onto the stack.  That will continue until you run out of stack space or your processes finally finish.  I'd put my money on stack space resource failure.

Your problem is compounded by the probability that your routines will change one or more cells in the same worksheet, causing another Worksheet_Change event - this time, not by the 3rd party app, but your own code!

===================
You might  consider adding another worksheet that will reflect the changes of both your 3rd party app and your own routines.  For instance, you create links between a workbook updated by the 3rd party app to another workbook that can be seen by the user.  The Worksheet_Change event kicks off code that updates the new workbook.  Thus, you avoid the problem of event cascade loops.

You might be able to get away with updating some other worksheets of a single workbook and reflect these changes in the same worksheet as are updated by the 3rd party app.

You might have to pass the Target parameter value to your routine.  Your routine can then ignore any Target range that it updates.

 

by: experts1Posted on 2009-10-23 at 10:49:23ID: 25646679

osknows,

Here is the model solution to control the madness of consecutive WorkSheet change events from the same worksheet:

We declare a public boolean variable for each worksheet and only start the sheet's subroutine if the associated boolean value is true, as per modified snippet below.

The sheet's process_sheetx variable is changed to false while associated subroutine is being processed and then reverted back to true at the end of subroutine.

Declare variables at top of ThisWorkbook Module!

Regards

Dim process_sheet1 as boolean
Dim process_sheet2 as boolean
Dim process_sheet3 as boolean
Dim process_sheet4 as boolean
Dim process_else as boolean
process_sheet1 = true
process_sheet2 = true
process_sheet3 = true
process_sheet4 = true
process_else = true
 
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
 
  Select Case Sh.Index
    Case 1
     If process_sheet1 then
      'call a subroutine to process sheet1
      subroutine_to_process_sheet1 (Sh.Index)
     End If
    Case 2
     If process_sheet2 then
      'call a subroutine to process sheet2
      subroutine_to_process_sheet1 (Sh.Index)
     End If
    Case 3
     If process_sheet3 then
      'call a subroutine to process sheet3
      subroutine_to_process_sheet1 (Sh.Index)
     End If
    Case 4
     If process_sheet4 then
      'call a subroutine to process sheet4
      subroutine_to_process_sheet1 (Sh.Index)
     End If
    Case Else
    If process_else then
     'call a subroutine to process all other sheets
     subroutine_to_process_sheet1 (Sh.Index)
    End If
  End Select
End Sub
 
Private Sub subroutine_to_process_sheet1(val As Integer)
process_sheet1 = false 'Disable a new instance to process sheet1
For i = 1 To 100000
    DoEvents
Next i
 
  MsgBox (val)
  
process_sheet1 = true  'Enable new instance to process sheet1
End Sub
 
Private Sub subroutine_to_process_sheet2(val As Integer)
process_sheet2 = false 'Disable a new instance to process sheet2
For i = 1 To 100000
    DoEvents
Next i
 
  MsgBox (val)
process_sheet2 = true  'Enable new instance to process sheet2
End Sub

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:

Select allOpen in new window

 

by: aikimarkPosted on 2009-10-23 at 11:12:38ID: 25646872

@experts1

Did you mean for your case clauses to invoke different subroutines?

=============
@osknows

What kind of processing do you need to do?
What is the relative priority of your processing vs. the 3rd party app updates?

 

by: osknowsPosted on 2009-10-23 at 11:21:07ID: 31644800

This is a neat solution!

 

by: osknowsPosted on 2009-10-23 at 11:23:50ID: 25646965

Yes, I potentially need to have different routines unique to each worksheet.

The type of processing is included below, essentially it reads a full range into an array, performs calcs and writes back to the worksheet. It's used for trigger trading on betfair

Private Sub Worksheet_Change(ByVal Target As Range)
 
 
 
        
   
    If Target.Columns.Count = 16 Then
        If Not refreshed Then
            refreshed = True
            dtStart = GetTickCount
            Set refreshTimes = New Collection
            refreshCount = 0
        Else
            dtEnd = GetTickCount
            refreshCount = refreshCount + 1
            elapsedTime = dtEnd - dtStart
            refreshTimes.Add Str(elapsedTime), Str(refreshCount)
            totRefresh = totRefresh + elapsedTime
            If refreshCount > avgCount Then
                totRefresh = totRefresh - Val(refreshTimes(Str(refreshCount - avgCount)))
                refreshTimes.Remove (Str(refreshCount - avgCount))
                 Application.EnableEvents = False
                Cells(2, 21).Value = totRefresh / avgCount
                Application.EnableEvents = True
            End If
            dtStart = dtEnd
        End If
 
 
 
Application.EnableEvents = False
 
    Cells(2, 10).Value = "U" 'updates balance and exposure
       
    'log time race went in play
    If Cells(2, 5).Value = "In Play" And Cells(3, 17).Value = "" Then
    Cells(3, 17).Value = Cells(2, 4).Value
    ElseIf Cells(2, 5).Value <> "In Play" Then
    Cells(3, 17).Value = ""
    End If
       
    'forward quick pick race on after race ended
    If Cells(2, 5).Value = "In Play" And Cells(2, 6).Value = "Suspended" And UCase(Cells(1, 17).Value) = "Y" And nextracetrigger = 0 Then
        nextracetrigger = 1
        lastrace = Cells(1, 1).Value
        Cells(2, 17).Value = -1
    End If
    
    If lastrace <> Cells(1, 1).Value Then
        nextracetrigger = 0
        Cells(2, 17).FormulaR1C1 = "=IF(OR(RC[-11]=""Suspended"",RC[-11]=""Closed""),1,IF(ISERROR(IF(AND(HOUR(RC[-13])=0,MINUTE(RC[-13])<=1),0.2,1)),0.2,IF(AND(HOUR(RC[-13])=0,MINUTE(RC[-13])<=1),0.2,1)))"
    End If
    
           
    If Range("e2") = "In Play" And Range("f2") <> "Suspended" Then
        Set rng = Range("a5:bz55")
        strArray = rng
        For i = 1 To UBound(strArray)
                
                'track lowest lay odds
                strArray(i, 70) = strArray(i, 8) '8 is col H, 70 is unused array address
                If (strArray(i, 8) - strArray(i, 53)) <> 0 Then
                strArray(i, 69) = strArray(i, 8) - strArray(i, 53)
                Else
                strArray(i, 69) = strArray(i, 54)
                End If
                
                strArray(i, 68) = strArray(i, 8)
                
                Select Case strArray(i, 52) '52 is col AZ
                Case "", Is > strArray(i, 8)
                If strArray(i, 8) <> 0 Then
                strArray(i, 70) = strArray(i, 8)
                Else
                strArray(i, 70) = 1001
                End If
                Case Else
                strArray(i, 70) = strArray(i, 52)
                End Select
                
        Next i
        slicestrArray = ThisWorkbook.Sheets(1).Range("az5:bb55")
        slicestrArray2 = UBound(slicestrArray)
        ReDim holdingarray(1 To slicestrArray2, 2)
        For i = 1 To UBound(strArray)
        holdingarray(i, 0) = strArray(i, 70)
        holdingarray(i, 1) = strArray(i, 68)
        holdingarray(i, 2) = strArray(i, 69)
        Next i
        ThisWorkbook.Sheets(1).Range("az5:bb55").Value = holdingarray
    Else
    Range("az5:az55").Value = 1001
    Range("ba5:bb55").Value = ""
    End If
Application.EnableEvents = True
End If
 
End Sub

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:

Select allOpen in new window

 

by: experts1Posted on 2009-10-23 at 11:32:07ID: 25647035

aikimark:

Yes, osknows seem to be doing different processes for each individual worksheet, thus my suggestion!

Regards

 

by: aikimarkPosted on 2009-10-23 at 11:42:08ID: 25647133

@experts1

>>osknows seem to be doing different processes for each individual worksheet
I posted my comment because your code invoked the same routine for each CASE clause.  Looking at the osknows code, I think the *same* process is applied to every worksheet after updating.  In that case, the event code might only need to invoke a single routine, if necessary, and pass a worksheet reference.

=======================
@osknows

You may want to ask a new question about making your process faster or more efficient.

 

by: osknowsPosted on 2009-10-23 at 12:03:42ID: 25647313

I do need the option of running seperate code per worksheet. Thank you both for your very valuable help.

Thank you
Os

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