Code to Lock and Unlock a sheet

  • Thread starter Thread starter Drew
  • Start date Start date
D

Drew

I'm sure that this is very basic code, but I am a newby to VBA. Currently I
have some code that is running that will update my pivot table when I click
on the tab where the pivot table resides (Sales). However, when I protect
this sheet, the code fails and I get an error. Can someone help me with the
code that I need to unprotect the sheet prior to the code that runs the pivot
table update and protect the sheet once the code is done running.

Thanks,
 
Using unprotect and reprotect creates risk of sheets being left unprotected
in the event of runtime errors unless you take considerable care in your
error handling.

Simpler solution is to protect with the property UserInterfaceOnly set to
true. e.g...

ActiveSheet.protect "password", UserInterfaceOnly:=True

This allows any running VBA code to make changes while the user cannot do so
directly. Items of note when using this method - it is not retained after
the workbook is closed, so you may want to include it in the workbook open
event. And it's occasionally a little quirky about not allowing certain
kinds of changes, (Copy and paste a range from unprotected source to
protected sheet - go figure).
 
Private Sub Worksheet_Activate()
Me.Unprotect Password:="drowssap"
'do your stuff code
Me.Protect Password:="drowssap"
End Sub


Gord Dibben MS Excel MVP
 
Back
Top