Sub Mymacro Sheet1.Unprotect Password: "Secret" 'Your Code Sheet1.Protect Password: "Secret" End Sub
Sub Mymacro Sheet1.Unprotect Password: "Secret" 'Your Code Sheet1.Protect Password: "Secret" End Sub
If you have ever tried to run an Excel macro on a worksheet thats been protected, you know that as soon as the worksheet is encountered, your macro
probably wont work and instead will display a runtime error.
One way to get around this is to use some code such as the following to
unprotect and then protect your worksheet:
Sub MyMacro( )
Sheet1.Unprotect Password:="Secret"
'YOUR CODE
Sheet1.Protect Password:="Secret"
End Sub
As you can see, the code unprotects Sheet1 with the password Secret, runs
the code, and then password-protects it again. This will work, but it has a
number of drawbacks. For one, the code could bug out and stop before it
encounters the Sheet1.Protect Password:="Secret" line of code. This, of
course, would leave your worksheet fully unprotected. Another drawback is
that you will need similar code for all macros and all worksheets.
Another way to avoid this problem is to use UserInterFaceOnly, which is an
optional argument of the Protect method that you can set to True. (The
default is False.) By setting this argument to True, Excel will allow all Excel
VBA macros to run on the worksheets that are protected with or without a
password.
However, if you use the Protect method with the UserInterfaceOnly argument set to True on a worksheet and then save the workbook, the entire
worksheet (not just the interface) will be fully protected when you reopen
the workbook. To set the UserInterfaceOnly argument back to True after the