I have an excel workbook that protects and hides all worksheets but one before the workbook is closed. On that one worksheet it is supposed to unprotect the sheet, clear out some cell values, then reprotect the sheet.
When I close the workbook with the X in the top corner the sub runs just fine. When I try to use ThisWorkbook.Close the sub does not actually unprotect the sheet so I get a Run-time error '1004' when it tries to clear the cell values.
I need the .Close method to work for another script which will close the workbook after x amount of time.
Before Close Script
Private Sub Workbook_BeforeClose(Cancel As Boolean)
ThisWorkbook.Unprotect Password:=pw
For Each Worksheet In ThisWorkbook.Worksheets
Worksheet.Protect Password:=pw
If Worksheet.Name = "Control Tab" Then
With Worksheet
.Unprotect Password:=pw
.Cells(24, 4).Value = ""
.Cells(24, 5).Value = ""
.Cells(24, 6).Value = ""
.Cells(24, 7).Value = ""
.Cells(24, 8).Value = ""
.Cells(24, 9).Value = ""
.Cells(24, 10).Value = ""
.Cells(24, 11).Value = ""
.Cells(24, 12).Value = ""
.Cells(24, 13).Value = ""
.Cells(24, 14).Value = ""
.Cells(24, 15).Value = ""
.Cells(24, 16).Value = ""
.Protect Password:=pw
End With
Else
Worksheet.Visible = 0
End If
Next
ThisWorkbook.Protect Password:=pw
ThisWorkbook.Save
End Sub
Button to close workbook (for testing)
Sub Button1_Click()
ThisWorkbook.Close
End Sub
I've tried to search for a reason why there might be a difference between problematically and manually closing a workbook on google and stackoverflow but haven't found any insight as to why the script won't unprotect the sheet. Any help would be greatly appreciated.