Disable cells

rahuldev31

New Member
Joined
Jan 11, 2025
Messages
1
Office Version
  1. 2021
Platform
  1. Windows
if i select an active cell as I9, then I4 to I8 . Likewise if i select another active cell in I, then need to freeze previous 5 cells from being cut,copy,paste or being edited
 

Excel Facts

Highlight Duplicates
Home, Conditional Formatting, Highlight Cells, Duplicate records, OK to add pink formatting to any duplicates in selected range.
VBA Code:
Option Explicit


Private Sub Worksheet_Change(ByVal Target As Range)
    Dim ws As Worksheet
    Dim rngProtect As Range
    Dim startRow As Long
    Dim endRow As Long

    ' Set the worksheet
    Set ws = Target.Worksheet

    ' Check if the change occurred in column I and the row is greater than or equal to 6
    If Target.Column = 9 And Target.Row >= 6 Then
        ' Calculate the range of the previous 5 cells directly above the selected cell
        startRow = Target.Row - 5
        endRow = Target.Row - 1
        Set rngProtect = ws.Range("I" & startRow & ":I" & endRow)

        ' Disable events to avoid recursion
        Application.EnableEvents = False

        ' Unprotect the sheet
        ws.Unprotect Password:="123" ' Replace "123" with your desired password

        ' Unlock all cells in the sheet
        ws.Cells.Locked = False

        ' Lock the cells in the specified range
        rngProtect.Locked = True

        ' Protect the sheet to enforce locking
        ws.Protect Password:="123", AllowSorting:=True, AllowFiltering:=True

        ' Re-enable events
        Application.EnableEvents = True
    End If
End Sub
 
Upvote 0

Forum statistics

Threads
1,226,108
Messages
6,188,978
Members
453,516
Latest member
torisemo

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