ZuriPow
ZuriPow

Reputation: 13

Proper VBA code to close workbook without saving

Whenever the code is executed while multiple workbooks are open, office stops working with a message

Microsoft Office Excel has stopped working

Windows can try to recover your information and restart the program.

What's wrong with the code? I'm using MS Office 2007 on Windows7

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    close_without_saving
End Sub

Sub close_without_saving()
    Application.DisplayAlerts = False
    ThisWorkbook.Saved = True

    If Application.Workbooks.Count < 2 Then
        Application.Quit
    Else
        ThisWorkbook.Close
    End If
End Sub

Upvotes: 1

Views: 86580

Answers (1)

skkakkar
skkakkar

Reputation: 2828

If you want to close the workbook without incorporating changes. Then you can use code like this in workbook module ~

Sub Auto_Close() 
    ThisWorkbook.Saved = True 
End Sub

You can also use this for closing workbook without saving changes.

Sub CloseBook2() 
    ActiveWorkbook.Close savechanges:=False 
End Sub

This routine can be attached to Close X Button. Workbook never closes partially, it will always close with all sheets contained in this workbook. DisplayAlerts = False and subsequently True can be incorporated in the routine. That should not create a problem like

Sub CloseBook() 
    Application.DisplayAlerts = False 
    ActiveWorkbook.Close 
    Application.DisplayAlerts = True 
End Sub 

Upvotes: 4

Related Questions