Excel VBA - protect worksheet but leave some cells unprotected

Harry Flashman

Active Member
Joined
May 1, 2011
Messages
356
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

Format cells as date
Select range and press Ctrl+Shift+3 to format cells as date. (Shift 3 is the # sign which sort of looks like a small calendar).

Harry Flashman

Active Member
Joined
May 1, 2011
Messages
356
Okay I figured it out. The Clear method clears all of the cells properties, including its protection. Thus I need to use .ClearContents instead.
 

Harry Flashman

Active Member
Joined
May 1, 2011
Messages
356
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
 

Watch MrExcel Video

Forum statistics

Threads
1,129,816
Messages
5,638,496
Members
417,029
Latest member
lingx86

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
Top