Closing workbook, catch Cancel event - excel

I have code for Workbook_BeforeClose event. I like how it works now but I have just noticed a problem with Application.Visible = False. When I click Yes, it saves Workbook, when I click No, it does nothing, but when I click Cancel it already done Application.Visible = False and I can't see Excel application. How to fix that?
Private Sub Workbook_BeforeClose(Cancel As Boolean)
On Error Resume Next
Application.Visible = False
Application.DisplayFormulaBar = True
ActiveWindow.DisplayHeadings = True
ActiveWindow.DisplayGridlines = True
ThisWorkbook.Unprotect Password:="123456"
ActiveWorkbook.Sheets("Start").Visible = True
ThisWorkbook.Worksheets("Start").Activate
ThisWorkbook.Protect Password:="123456", Structure:=True, Windows:=False
End Sub

Instead of relying on the built-in dialog, try using your own. That way you have more control of what happens and when.
So maybe something like:
Dim closing As Boolean
Private Sub Workbook_BeforeClose(Cancel As Boolean)
If Not closing Then
answer = MsgBox("Save data?", vbYesNoCancel + vbQuestion, "Save data?")
If answer = vbYes Or answer = vbNo Then
closing = True
' your code here
ActiveWorkbook.Close savechanges:=answer = vbYes
Else
Cancel = True
End If
End If
End Sub

Related

Exit but still saving even when user selects to cancel

I have an odd thing (I think) but probably doing something incorrectly here. I am trying to force the user to enter in certain information in excel. The msgbox comes up with the OK/Cancel buttons but when either is selected the workbook saves and exits. If they cancel then I want it to sit on the cell where the issue is. Any help would be appreciated
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
'---------------------------
'-- Missing Employee Name --
'---------------------------
If Cells(5, 2).Value = Empty Then
If Not MsgBox("Employee Name missing! Pressing OK will exit without saving.", vbOKCancel, "The Mill") = vbOK Then
With Sheets("sheet1")
.Activate
.Cells(5, 2).Activate
End With
Cancel = True
Exit Sub
End If
End If
End Sub
I think the problem is that you aren't handling Workbook_BeforeClose, which triggers as you try to close the workbook.
So while the save is canceled, the close is not.
Moving everything to Workbook_BeforeClose and handling it there kind of works, until the user saves manually. So you will still have to handle that in the before save event.
This is an example:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
If Cells(5, 2).Value = Empty Then
If MsgBox("Employee Name missing! Pressing OK will exit without saving.", vbOKCancel, "The Mill") = vbOK Then
Application.DisplayAlerts = False
Application.Quit
Else
Sheets("Sheet1").Cells(5, 2).Activate
Cancel = True
End If
End If
End Sub
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
If Cells(5, 2).Value = Empty Then
Cancel = True
MsgBox "Employee Name missing!"
Sheets("Sheet1").Cells(5, 2).Activate
End If
End Sub
The only caveat I have seen, is that Application.DisplayAlerts = False will affect other open workbooks.

Excel own dialog box on Workbook_BeforeClose event, option for Cancel

My code looks like this now, the only problem left to solve is how to get Cancel without displaying built-in dialog box. If I click Yes or No, everything works fine. However when I click Cancel built-in dialog box pops up and I have to click Cancel again. How to make Cancel work like Cancel, so there wouldn't be built-in dialog box popping up?
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Application.DisplayAlerts = False
If Not closing Then
answer = MsgBox("Save data?", vbYesNoCancel + vbQuestion, "Save data?")
If answer = vbYes Or answer = vbNo Then
closing = True
On Error Resume Next
Application.Visible = False
Application.DisplayFormulaBar = True
ActiveWindow.DisplayHeadings = True
ActiveWindow.DisplayGridlines = True
ThisWorkbook.Unprotect Password:="123456"
ActiveWorkbook.Sheets("Start").Visible = True
ThisWorkbook.Worksheets("Start").Activate
ThisWorkbook.Protect Password:="123456", Structure:=True, Windows:=False
ActiveWorkbook.Close savechanges:=answer = vbYes
Else
Cancel = True
End If
End If
Application.DisplayAlerts = True
End Sub
Here is how it looks like (I use Office 2016):
This is the problem: ActiveWorkbook.Close savechanges:=answer = vbYes
It fires the BeforeClose event again. So you should disable the events beforehand and re-enable them afterwards.
Application.EnableEvents=False
ActiveWorkbook.Close savechanges:=answer = vbYes
Application.EnableEvents=True

Cancel = True is not working in Workbook_BeforeClose

This clearly shows that value of cancel is true, and still my workbook closes after this! Why?
I want to cancel closing of the excel file if user input is incorrect.
I debug the code and found out that the value of Cancel was initially False, and it becomes True. But once the Sub ends, file is still closed.
(variable error is defined at workbook declaration space, so accessible within module.)
Private Sub Workbook_BeforeClose(Cancel As Boolean)
error = 0
check_for_error
If error = 1 Then
Cancel = True
Exit Sub
End If
Application.EnableEvents = False
Sheet1.Cells.ClearContents
Sheet2.Cells.Clear
Application.EnableEvents = True
End Sub
I want to cancel closing of file if error = 1.
Update:: Thanks everyone for the responses, but nothing seems to work for me! Following is how my current code looks.
Option Explicit
Dim errYes As Byte
Private Sub Workbook_BeforeClose(Cancel As Boolean)
check_freeze_panel
If errYes = 1 Then
Cancel = True
Exit Sub
End If
Application.DisplayAlerts = False
ThisWorkbook.Save
Application.DisplayAlerts = True
End Sub
errYes is returning 1, Cancel = True is being executed, and still my workbook closes.
I even tried commenting all the code, and just putting Cancel = True as suggested and guess what, it still closes!
Change the name of error this is a reserved word for an already existing function (see Error function) and must not be used as a variable name. And activate Option Explicit and declare all your variables.
Here is an example how you would do it correctly:
Option Explicit
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Dim ErrorsFound As Boolean
ErrorsFound = check_for_error
If ErrorsFound Then
Cancel = True
Exit Sub
End If
Application.EnableEvents = False
Sheet1.Cells.ClearContents
Sheet2.Cells.Clear
Application.EnableEvents = True
End Sub
Function check_for_error() As Boolean
'check and return
check_for_error = True 'errors found
End Function
Or even shorter:
Option Explicit
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Cancel = check_for_error
If Not Cancel Then
Application.EnableEvents = False
Sheet1.Cells.ClearContents
Sheet2.Cells.Clear
Application.EnableEvents = True
End If
End Sub
Function check_for_error() As Boolean
'check and return
check_for_error = True 'errors found
End Function
Try this. Set Error equal to your function call and make sure it returns the right data type.
Private Sub Workbook_BeforeClose(Cancel As Boolean)
error = check_for_error
If error = 1 Then
Cancel = True
Exit Sub
End If
Application.EnableEvents = False
Sheet1.Cells.ClearContents
Sheet2.Cells.Clear
Application.EnableEvents = True
End Sub
Initially Cancel is equal False, means File Close will succeed.
For me the below code works fine. When I set error = 1 then closing is cancelled whether you use "Exit Sub" or not. When I set error <> 1 then cls
When I test your Code:
Option Explicit
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Dim error As Integer
error = 1
If error = 1 Then
Cancel = True
'Exit Sub
End If
End Sub
Just test this:
Write False and workbook should Close, and True should "stop" the closing.
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Cancel = False
End Sub

how to renable the close [x} button of excel

I have this code that disable the close [x] function of excel. after completed enter ID, I need to enable again the button.
I have this part that disable the [x],
Public FlagToClose As Boolean
Sub Enter_1()
FlagToClose = False
'code
'.....................
FlagToClose = True
End Sub
for the workbook module I have this,
Private Sub Workbook_Open()
FlagToClose = True
End Sub
Private Sub Workbook_BeforeClose(Cancel As Boolean)
If Not FlagToClose Then Cancel = True
End Sub
then how to enable again the close[x] function?
To re-enable closing, run this short macro before closing:
Sub ev_off()
Application.EnableEvents = False
End Sub

VBA Excel-How to work with cancel button in the MS Excel close?

I am running a macro while in Private Sub Workbook_BeforeClose(Cancel As Boolean)
but whenever user clicks on Cancel button macro should not run.
I kept following lines of code
Private Sub Workbook_BeforeClose(Cancel As Boolean)
If Cancel = True Then
MsgBox "You clicked on Cancel"
ElseIf Cancel = False Then
Call SDA
End If
End SubBut whenever i press Cancel button it is not showing me any MessageBox.Any help would be appreciated greatly.
Try this please:
Option Explicit
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Dim Msg As String
Dim ireply As Integer
If Not Me.Saved Then
Msg = "Do you want to Save this book? "
ireply = MsgBox(Msg, vbQuestion + vbYesNoCancel)
Select Case ireply
Case vbYes
Me.Save
Call SDA
Case vbNo
Me.Saved = True
Case vbCancel
Cancel = True
MsgBox "Cancelling...workbook close event!"
Exit Sub
End Select
End If
End Sub
Output dialogs:
The usual structure of a messagebox cancel event wrap is as follows:
'--Display MessageBox
Dim intMsg as integer
intMsg = MsgBox(strPrompt, vbYesNo, strTitle)
'--Check pressed button
If iRet = vbNo Then
MsgBox "NO!"
Else
MsgBox "Yes!"
End If

Resources