How to stop closing all workbook after hitting X sign on top right corner.

dmadhup

Board Regular
Joined
Feb 21, 2018
Messages
146
Office Version
  1. 365
I have two Excel file, the first one has no macro on it and the second one has a macro on it. First, i open the spreadsheet which has no macro on it. Then I open the second excel which has a macro on it. Now if I hit the X sign on the top right corner to close my first spreadsheet then it closes then it invokes the following macro of another spreadsheet. Means it force to close another spreadsheet which has following macro on it.

How can I stop to invoke the following sub upon closing the first spreadsheet?
Private Sub Workbook_BeforeClose(cancel As Boolean)

End Sub
 

Excel Facts

Do you hate GETPIVOTDATA?
Prevent GETPIVOTDATA. Select inside a PivotTable. In the Analyze tab of the ribbon, open the dropown next to Options and turn it off
Welcome to the Forum!

I'm not totally clear what you're asking, but I think you're saying that if a particular workbook is not the ActiveWorkbook, and the user closes Excel, then that workbook should always remain open?

In which case, try:

Code:
'Code Module
Public bOtherWorkbook As Boolean
'ThisWorkbook Module
Private Sub Workbook_Activate()

    bOtherWorkbook = False

End Sub
Private Sub Workbook_BeforeClose(Cancel As Boolean)

    Dim wb As Workbook
    
    Cancel = bOtherWorkbook
    
    If Cancel Then
        Application.ScreenUpdating = False
        For Each wb In Workbooks
            If wb.Name <> ThisWorkbook.Name Then wb.Close
        Next
        Application.ScreenUpdating = True
    End If
    
End Sub
Private Sub Workbook_Deactivate()

    bOtherWorkbook = True
    
End Sub

For all other workbooks where changes have been made, you should get the usual dialog box allowing you to save changes or cancel the close.
 
Upvote 0

Forum statistics

Threads
1,224,822
Messages
6,181,165
Members
453,021
Latest member
Justyna P

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