Problem with Workbook_BeforeSave event

T

tempest0123

Hi all.

I have noticed that Workbook_BeforeSave event does not work properly
if the workbook is closed by a VBA macro of another workbook or by an
external VB program.

For example, suppose I have the following two simple event procedures
in ThisWorkbook module:

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As
Boolean)
MsgBox("BeforeSave event triggered")
End Sub

Private Sub Workbook_BeforeClose(Cancel As Boolean)
'Do something processing here such as hide certain worksheets and
protect the workbook
MsgBox("Before Me.Save")
Me.Save
MsgBox("After Me.Save")
End Sub

If I close the workbook manually in Excel, I would see the all three
MsgBox displays and the worksheets I specified in the code would be
hidden in the saved file.

Now, suppose I have created an external VB program containing the
following codes:

Sub Main()
Dim xlApp as Object
Dim xlWorkbook as Object
Set xlApp = CreateObject("Excel.Application")
xlApp.Open FileName:="SomeTestFile.xls"
Set xlWorkbook = xlApp.Workbooks(1)
xlWorkbook.Close
xlApp.Close
Set xlWorkbook = Nothing
Set xlApp = Nothing
End Sub

This simple program is supposed to create an Excel application object,
open a workbook, and then close the workbook. I was expecting all
workbook events procedures would run as if I opened and closed the
workbook manually.

However, when I run the program, I only see "Before Me.Save" and
"After Me.Save" msgboxes displayed. I did not see "BeforeSave event
triggered" message displayed so that implies the BeforeSaveEvent was
never triggerd. And afterward, Excel would display the "Do You want
to save changes made in the workbook" message. If I select Yes to
save the changes, worksheets that should have been hidden
Workbook_BeforeClose proecdure are still visible in the saved file.

Does anyone know if there is any known problem with
Workbook_BeforeClose event procedure?

Thanks.
Jason
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top