PDA

View Full Version : Is there any event allowing Cancel of closing a Window (not closing a Workbook)?



LarryG
11-09-2019, 10:16 PM
(FYI this is different than my recent post) If I open two windows on one workbook, such as
Control-N
alt-W-N
then you can close a Window with Control-F4 or Control-W. The workbook is still open but the window closes. So you'd be closing Book1:2 but book1.xls is still open.
I want to Cancel that closing if certain conditions are true. Can I?

The only event that I know of when you close a window is App_WindowDeactivate. However, it doesn't seem to be Cancel-able. Also a problem is that that event happens every time you flip to another window or workbook. I'm only interested in acting on the case where a Window is being closed, such as by Control-F4 or Control-W, but I don't see how to identify that the user has gone (e.g.) Control-F4, as opposed to Control-Tab or something (that's not Closing the window).

All this is for MDI versions of Excel, prior to when they destroyed a lot of VBA code with SDI -- 2013 IIRC.

Leith Ross
11-10-2019, 11:19 AM
Hello LarryG,

There are no native VBA events for closing a Window. However, you could intercept the close message by sub-classing the Window Procedure for the window you don't want to close. This requires writing VBA macros that call the Windows API. If you are not familiar with the Windows API and Window objects then you will need to work with someone who does.

LarryG
11-10-2019, 01:52 PM
Leith - thanks for the comment. I've implemented a few things like SetEnvironmentVariable, GetForegroundWindow, GetAsyncKeyState, SetWindowPos. I struggle with Callbacks, and hooks scare me, but other than that, doing them in VBA _seems_ easy. And VBA seems quite forgiving; long ago I would write API calls in C and data types (short/int/long/HWND/whatever) could really kill you but to my recollection VBA doesn't seem to. Maybe it's just because I've been 32 for ages (though I also use 64 Win 10 and XL16).