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

What is =ROMAN(40) in Excel?
The Roman numeral for 40 is XL. Bill "MrExcel" Jelen's 40th book was called MrExcel XL.
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,214,839
Messages
6,121,891
Members
449,058
Latest member
Guy Boot

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