You can change the sheet through the code by following these steps.
In the code, it will be:
Sub UnProtect_Modify_Protect() ThisWorkbook.Worksheets("Sheet1").Unprotect Password:="Password" 'Unprotect ThisWorkbook.ActiveSheet.Range("A1").FormulaR1C1 = "Changed" 'Modify ThisWorkbook.Worksheets("Sheet1").Protect Password:="Password" 'Protect End Sub
The weakness of this method is that if the code is interrupted and error handling does not capture it, the worksheet can be left in an unprotected state.
The code can be improved by following these steps.
Code for this:
Sub Re-Protect_Modify() ThisWorkbook.Worksheets("Sheet1").Protect Password:="Password", _ UserInterfaceOnly:=True 'Protect, even if already protected ThisWorkbook.ActiveSheet.Range("A1").FormulaR1C1 = "Changed" 'Modify End Sub
This code updates the protection on the worksheet, but with the UserInterfaceOnly parameter set to true. This allows the VBA code to modify the worksheet, keeping the personal sheet protected from user input through the user interface, even if execution is interrupted.
This parameter is lost when the workbook is closed and reopened. Worksheet protection is retained.
Therefore, the Re-Protection code should be included at the beginning of any procedure that tries to change the worksheet or can only be run once when the workbook is opened.
Robert Mearns Sep 24 '08 at 12:14 2008-09-24 12:14
source share