Protect Workbook cells by color

raj08536

Active Member
Joined
Aug 16, 2007
Messages
322
Office Version
  1. 365
Platform
  1. Windows
I have found following code to cell protect by color. It only work for activesheet. Can we expand for active workbook?

Sub Lock_Color()
Dim colorIndex As Integer

Dim Range As Range
'Lock all the cells that are selected color

colorIndex = 6 '6 = yellow
For Each Range In ActiveSheet.UsedRange.Cells
Dim color As Long
color = Range.Interior.colorIndex
If (color = colorIndex) Then
Range.Locked = True
Else
Range.Locked = False
End If
Next Range
'Protect worksheet
ActiveSheet.Protect Password:="123456", DrawingObjects:=True, Contents:=True, Scenarios:=True _
, AllowSorting:=True, AllowFiltering:=True, AllowUsingPivotTables:=True
MsgBox "Highlighted cells are locked!"
End Sub
 

Excel Facts

Copy PDF to Excel
Select data in PDF. Paste to Microsoft Word. Copy from Word and paste to Excel.
This code seems to actually be Protecting the entire sheet vs just those specific cells which are yellow, it locks the specific cells but locks the entire sheet. Just in case someone else reading this decides to use this code.

Here is the revised version that would run all sheets vs just the active sheet.
VBA Code:
Sub Lock_Color()
Dim colorIndex As Integer

Dim Range As Range
'Lock all the cells that are selected color

colorIndex = 6 '6 = yellow

For i = 1 To ActiveWorkbook.Worksheets.Count
For Each Range In Sheets(i).UsedRange.Cells

Dim color As Long
color = Range.Interior.colorIndex
If (color = colorIndex) Then
Range.Locked = True
Else
Range.Locked = False
End If
Next Range
'Protect worksheet
Sheets(i).Protect Password:="123456", DrawingObjects:=True, Contents:=True, Scenarios:=True _
, AllowSorting:=True, AllowFiltering:=True, AllowUsingPivotTables:=True
MsgBox "Highlighted cells are locked!"
Next i
End Sub
 
Upvote 0

Forum statistics

Threads
1,214,805
Messages
6,121,664
Members
449,045
Latest member
Marcus05

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