Excel VBA - protect worksheet but leave some cells unprotected

Harry Flashman

Active Member
Joined
May 1, 2011
Messages
361
I have a worksheet that I want to protect, but leave some cells unprotected. Normally what Is right-click the cells I wish to leave unprotected, choose format/protection and then untick locked.

I have a macro that clears the unprotected range:

Code:
Sub ClearPasteRange()
Dim ws As Worksheet
Dim MyRng As Range
Set ws = Worksheets("Chart")
ws.Unprotect
Set MyRng = ws.Range("MyPasteRange")
MyRng.Clear
Calculate
ws.Protect
End Sub

The thing is the range I wished to leave unprotected MyPasteRange ends up being protected again after the macro is run. That is the cells properties change to being locked again.

It doesn't happen if I manually unprotect/protect the worksheet. It only happens when I run the macro.
Is this usual? Where am I going wrong.

Edit: I have just realized something silly. I don't need to unprotect the sheet in my macro. doh!
Still I am curious about this behaviour from the macro.
 
Last edited:

Excel Facts

Easy bullets in Excel
If you have a numeric keypad, press Alt+7 on numeric keypad to type a bullet in Excel.
Okay I figured it out. The Clear method clears all of the cells properties, including its protection. Thus I need to use .ClearContents instead.
 
Upvote 0
Actually that was wrong too. I also wanted to clear the formats. This code works:

Code:
Sub ClearPasteRange()
Dim ws As Worksheet
Dim MyRng As Range
Set ws = Worksheets("Chart")
ws.Unprotect
Set MyRng = ws.Range("MyPasteRange")
With MyRng
    .Clear
    .Locked = False
End With
    
Calculate
ws.Protect

End Sub
 
Upvote 0

Forum statistics

Threads
1,224,271
Messages
6,177,611
Members
452,785
Latest member
3110vba

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top