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
Related
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
Right now my process is working correctly, with the help of this community, however, I need this Worksheet_Calculate to NOT execute the Macro (MacroRuns for example) when the workbook opens, but I still need it to function the same way it is currently, after the workbook is opened.
Thank you so much for your help in advance!
The Code I Am Using:
in ThisWorkbook
Option Explicit
Private Sub Workbook_Open()
TargetStart
End Sub
in the target sheet's code window
Option Explicit
Private Sub Worksheet_Calculate()
Application.EnableEvents = False
TargetCalc Me
Application.EnableEvents = True
End Sub
in Module 1
Option Explicit
Public TargetValue As Variant
Private Const cTarget As String = "C3"
Sub TargetCalc(ws as Worksheet)
If ws.Range(cTarget) <> TargetValue Then
'this is where I would like the code to say something like, "if workbook just opened, exit -- otherwise continue. If this is even possible.
Call MacroRuns
TargetValue = ws.Range(cTarget).Value
End If
End Sub
Sub TargetStart()
TargetValue = Sheet1.Range(cTarget).Value
End Sub
Sub MacroRuns()
Call UpdateMsgBox
End Sub
I think that this can solve your problem:
In ThisWorkbook:
Private Sub Workbook_Open()
Worksheets("NameHere").Range("A1") = True
End Sub
In the target sheet's code window:
Private Sub Worksheet_Calculate()
If Worksheets("NameHere").Range("A1") Then MacroRuns
Worksheets("NameHere").Range("A1") = False
End Sub
Please try this arrangement.
Public StartUp As Boolean
Private Sub Workbook_Open()
StartUp = True
TargetStart
End Sub
Sub TargetCalc(ws As Worksheet)
If ws.Range(cTarget) <> TargetValue Then
If Not StartUp Then MacroRuns
StartUp = False
TargetValue = ws.Range(cTarget).Value
End If
End Sub
or, perhaps you prefer it to be like this.
Sub TargetCalc(ws As Worksheet)
If ws.Range(cTarget) <> TargetValue Then
If Not StartUp Then
MacroRuns
TargetValue = ws.Range(cTarget).Value
End If
StartUp = False
End If
End Sub
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
I have a problem in Excel 2013. Yesterday I put the following code in Excel by rightclicking the tab of my worksheet (Alt-F11) :
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
If Not Intersect(Target, Range("D3:T42")) Is Nothing Then
Application.EnableEvents = False
If Target.Value = ChrW(&H2713) Then
Target.ClearContents
Cancel = True
Else
Target.Value = ChrW(&H2713)
Cancel = True
End If
End If
Application.EnableEvents = True
End Sub
This code is supposed to add a checkmark in the defined cells after double clicking. While this code worked fine yesterday, it now does not work anymore. I have tried everything but just do not get it to work. Any ideas ?
PS I would like to use such a code since a sheet with many form checkboxes makes it very slow (at least in my case)
Regards, Arno
Some error in one test may have made EnableEvents keep false eternally.
Run a single sub with Application.EnableEvents = true and test it again.
If that is false, no event will be thrown at all, no clicks, no double clicks, nothing will work.
I suggest you add an On error goto statement, to avoid that kind of problem:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
On Error goto 1
If Not Intersect(Target, Range("D3:T42")) Is Nothing Then
Application.EnableEvents = False
If Target.Value = ChrW(&H2713) Then
Target.ClearContents
Cancel = True
Else
Target.Value = ChrW(&H2713)
Cancel = True
End If
End If
on error goto 0
1 Application.EnableEvents = True
End Sub
This question already has answers here:
Making fields mandatory of a specific sheet on workbook save
(3 answers)
Closed 8 years ago.
I want to call this Sub in the Workbook_BeforeSave event:
Sub test()
If ActiveSheet.Range("A4") = "" Then
MsgBox ("Please fill in cell A4!")
Exit Sub
Else
End If
End Sub
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
test
End Sub
When I click save the file is saved even if the cell A4 is blank.
You should set Cancel as the proper way to terminate the save event.
It would be better to have test as a function, so you can check the return value, and set cancel appropriately.
Function test() as Boolean
If ActiveSheet.Range("A4") = "" Then
Test = False
Else
Test = True
End If
End Sub
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
If test = False then Cancel=True
End Sub
Also, ActiveSheet is not appropriate, unless you have only one worksheet, and you have protected the workbook from having extra sheets added.
My suggested solution would be to check Sheets("MySheet").Range("A4").
Of course, the laziest way to do the test would be:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
cancel = (ActiveSheet.Range("A4") = "")
End Sub
where the test is done within the save procedure, and no sub tests are required.
Try:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Call test
End Sub
Sub test()
If ActiveSheet.Range("A4") = "" Then
MsgBox ("Please fill in cell A4!")
End
End If
End Sub
Exit Sub merely terminates sub test(), while End completely stops code execution, thus preventing Workbook_BeforeSave() from running further.
if cancel is true, the saving will be blocked :
Sub Test(byref cancel as boolean)
If ActiveSheet.Range("A4") = "" Then
MsgBox ("Please fill in cell A4!")
cancel = true
Exit Sub
'Else
End If
End Sub
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Test Cancel
End Sub