ExcelBanter

ExcelBanter (https://www.excelbanter.com/)
-   Excel Programming (https://www.excelbanter.com/excel-programming/)
-   -   Worksheet.Unprotect within WorkbookBeforeSave event fails if Save initiated by VB (https://www.excelbanter.com/excel-programming/390943-worksheet-unprotect-within-workbookbeforesave-event-fails-if-save-initiated-vbulletin.html)

Dean Meyer

Worksheet.Unprotect within WorkbookBeforeSave event fails if Save initiated by VB
 
I trap the WorkbookBeforeSave event successfully and reliably.

Within that event-handling code, I use the Worksheet.Unprotect method.

In the Workbook object:
Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As
Boolean)
Cancel = WorkbookBeforeSave(ThisWorkbook, SaveAsUI)
End Sub

In a general module:
Function WorkbookBeforeSave(TargetWorkbook As Workbook, Optional
ByVal SaveAsUI As Boolean) As Boolean
...
TargetWorkbook.Worksheet(1).Unprotect
If TargetWorkbook.Worksheets(1).ProtectContents
Then
i = MsgBox("Failed to unprotect", vbOKOnly,
"DEBUG")
End If
...
End Sub

Unprotect works perfectly reliably when the user initiates the save.

Unprotect reliably fails (with no error message) when the save is
initated by my VB code.
Sub Test()
TargetWorkbook.Save
End Sub

Any idea why? Any work-around?

BTW, I absolutely do not want to disable users' ability to save in the
manner they're familiar with, replacing the usual button with my own
Save command as some have suggested. This application must be easy to
use and compatible with other spreadsheets.


Dean Meyer

Worksheet.Unprotect within WorkbookBeforeSave event fails if Save initiated by VB
 
My current solution: If VB wants to save, calls a procedure that
includes:

Sub FileSave(TargetWorkbook as Workbook)
If Not WorkbookBeforeSave(TargetWorkbook ) Then
Application.EnableEvents = False
TargetWorkbook .Save
Application.EnableEvents = True
End If



Dean Meyer

Worksheet.Unprotect within WorkbookBeforeSave event fails if Save initiated by VB
 
My current solution: If VB wants to save, calls a procedure that
includes:

Sub FileSave(TargetWorkbook as Workbook)
If Not WorkbookBeforeSave(TargetWorkbook ) Then
Application.EnableEvents = False
TargetWorkbook .Save
Application.EnableEvents = True
End If



Dean Meyer[_2_]

Worksheet.Unprotect within WorkbookBeforeSave event fails if Save
 
My current solution: If VB wants to save, calls a procedure that
includes:

Sub FileSave(TargetWorkbook as Workbook)
If Not WorkbookBeforeSave(TargetWorkbook ) Then
Application.EnableEvents = False
TargetWorkbook .Save
Application.EnableEvents = True
End If


All times are GMT +1. The time now is 10:01 PM.

Powered by vBulletin® Copyright ©2000 - 2025, Jelsoft Enterprises Ltd.
ExcelBanter.com