I thought that the code (including the userform) would be a different workbook.
From the sound of it, I was wrong.
Anyway:
Private Sub CloseYes_Click()
Application.EnableEvents = False
ActiveWorkbook.Close savechanges:=False 'false to close without save
Application.EnableEvents = True
End Sub
Causes a problem.
You disable events, then you close the workbook that's running the code. So
that last line is never run. So the events are kept disabled.
Try this:
Put this in a general module:
Option Explicit
Public blkEvents As Boolean
(blkEvents will now be "visible" everywhere in your code.)
Then in the workbook_beforeclose:
Option Explicit
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Cancel = Not blkEvents
If blkEvents = False Then
MsgBox "Must use Close Document button on Tax Invoice Sheet!"
End If
End Sub
and finally in your button click:
Option Explicit
Private Sub CloseYes_Click()
blkEvents = True
ActiveWorkbook.Close savechanges:=False 'false to close without save
End Sub
So instead of using excel's application.enableevents to stop the save, we do it
with our own variables.
And I don't care what happens to them when we close the workbook.
rob said:
Thanks Dave for your valuable input! I appreciate that it may be better to
have a button to create the workbook from the template which I may
implement after I have the rest working properly.
The Workbook is created initually from a template which is just opened from
File/New option on menu bar.
I still have one problem with the procedure, however.
I have fiddled around with your earlier code (removing all the first part)
and have it running very nicely.
The problem I have is that on first opening of the file, the beforeClose
event works great. BUT... after I close the file with the procedure stated
above, and reopen it again, the BeforeClose event does not occur. (The file
closes without any prompts). It will only work again if I completely close
down Excel and then reopen the file. I presume this is not a problem with
the code but rather a bug in Excel which I hope is not the case. Could you
look at or try this and see what the problem might be.
If its easier, I could attach a semblance of the file with just the
necessary close and BeforeClose codes and buttons there-in (only 27kb) or,
all the code I have in the test file is set out below.
This is what I have on a test workbook.....