Peculiar excel event behaviour

Jaafar Tribak

Well-known Member
Joined
Dec 5, 2002
Messages
7,929
Office Version
  1. 2016
Platform
  1. Windows
Hi all.

I have this simple code in ThisWorkbook module that is supposed to hook the Apllication events so that the AppEvents_WorkbookBeforeClose event hadler is fired each time an open workbook is closed.

Code:
Option Explicit
 
Private WithEvents AppEvents As Application
 
Private Sub Workbook_Open()
 
    Set AppEvents = Application
    
    Call MyLoop
 
End Sub

Private Sub AppEvents_WorkbookBeforeClose _
(ByVal Wb As Workbook, Cancel As Boolean)
 
    MsgBox "Workbook " & Wb.Name & " closing..."
 
End Sub
 
Private Sub MyLoop()
 
    Do
        DoEvents
    Loop
 
End Sub

Now the problem I am having is that if I close a workbook, the BeforeClose event code fires as expected but if I close the main Excel application window, the routine never gets fired.

I know this is due to the background loop routine because when I remove the loop routine everything works as expected.

Can anybody shade some light as to why this is happening and perhaps provide a workaround .

Thanks .
 

Some videos you may like

Excel Facts

What do {} around a formula in the formula bar mean?
{Formula} means the formula was entered using Ctrl+Shift+Enter signifying an old-style array formula.

Jaafar Tribak

Well-known Member
Joined
Dec 5, 2002
Messages
7,929
Office Version
  1. 2016
Platform
  1. Windows
Thanks Mike but that made no difference.
 

RoryA

MrExcel MVP, Moderator
Joined
May 2, 2008
Messages
35,493
Office Version
  1. 365
  2. 2019
  3. 2016
  4. 2010
Platform
  1. Windows
  2. MacOS
This is a bit of a guess, but I would suspect that the abrupt termination of the loop codde causes a reset and your application variable to lose state.
 

Jaafar Tribak

Well-known Member
Joined
Dec 5, 2002
Messages
7,929
Office Version
  1. 2016
Platform
  1. Windows
This is a bit of a guess, but I would suspect that the abrupt termination of the loop codde causes a reset and your application variable to lose state.

Thanks Rory. That is what I thought .

I really need that loop so I am still trying to solve this problem. If I come to a solution i'll post it here.
 

Watch MrExcel Video

Forum statistics

Threads
1,108,645
Messages
5,524,054
Members
409,557
Latest member
Excelinho

This Week's Hot Topics

Top