I have the following example code in a module of VBA:
Sub My_Code()
ThisWorkbook.Sheets("Main").Range("A1") = "Main Data"
ThisWorkbook.Sheets("Secondary").Range("A2").Copy Sheets("Main").Range("B2")
End Sub
and to protect the sheets, Main and Secondary, I have put the following code in Thisworkbook of VBA:
Private Sub Workbook_Open()
Sheets("Main").Protect Password:="Mypassword", UserInterfaceOnly:=True
Sheets("Secondary").Protect Password:="Mypassword", UserInterfaceOnly:=True
End Sub
When I run My_Code()
I get the error:
""Run-time error '1004' The cell or chart you're trying to change is on a protected sheet. To make changes, click Unprotect Sheet in the Review tab (you might need a password).""
And this debugs to the ThisWorkbook.Sheets("Secondary")....
line.
When I manually Unprotect the Main sheet the code runs. Any ideas why I can't leave Main protected? Have I forgotten something?
UserInterfaceOnly
part of the protection it is quite possible thatUserInterfaceOnly
isn't set to theTrue
that you think it is. Check that there are no other alternative passwords or protections being set elsewhere in your code and that the user isn't over-riding it. – CLRPrivate sub Workbook_Open()
which is run when the work book is opened, so theUserInterfaceOnly
is set true every time the workbook is opened. – sheds141Workbook.Activate
event instead ofWorkbook.Open
. I've never looked into why other than they have similar issues to you but this might be something to try? – CLR