Peculiar excel event behaviour

Jaafar Tribak

Well-known Member
Joined
Dec 5, 2002
Messages
9,621
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 .
 

Excel Facts

Bring active cell back into view
Start at A1 and select to A9999 while writing a formula, you can't see A1 anymore. Press Ctrl+Backspace to bring active cell into view.
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.
 
Upvote 0
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.
 
Upvote 0

Forum statistics

Threads
1,214,991
Messages
6,122,628
Members
449,095
Latest member
bsb1122

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top