Moto
Moto

Reputation: 1141

VSTO - Abort opening an Excel workbook

I have an Excel 2016 workbook that does some validation on opening. I'm using VSTO, here's a snippet of the code:

Private Sub ThisWorkbook_Open() Handles Me.Open
    Try
        If (DoNotOpen()) Then
            Me.Close() 'this throws a System.Threading.ThreadAbortException
...

The exception that occurs cannot be swallowed, as it will be re-thrown, as explained here. I understand why the exception is thrown (because closing the workbook before finishing opening it). I'm looking for the best way to abort opening (I found that I could altogether close Excel programmatically, by executing Me.Application.Quit, but I'm not entirely comfortably doing so because the code does not exit properly). Thank you in advance.

Upvotes: 0

Views: 217

Answers (1)

Maarten van Stam
Maarten van Stam

Reputation: 1899

Instead of trying to close the (half) opened workbook think about working the other way around. Only activate (add) the event handler when you think it should be active to only open the proper workbooks.

There are other known alternatives where the open event is in place, some very tricky, like activating a Timer when DoNotOpen() is in place, hiding the opened workbook and a bit later when the timer triggered closing the opened workbook or just open the workbook set invisible and close when Excel closes without saving the hidden workbooks.

Upvotes: 0

Related Questions