QP School
Protect specific cells with VBA - Printable Version

+- QP School (https://qomplainerzschool.lima-city.de)
+-- Forum: Tutorials (https://qomplainerzschool.lima-city.de/forumdisplay.php?fid=3)
+--- Forum: Excel VBA Tutorials (https://qomplainerzschool.lima-city.de/forumdisplay.php?fid=48)
+--- Thread: Protect specific cells with VBA (/showthread.php?tid=5260)



Protect specific cells with VBA - Qomplainerz - 07-27-2023

Example:

Sub ProtectSpecificCells()
    Dim ws As Worksheet
    Dim protectedRange As Range

    'Set the worksheet where the cells are located
    Set ws = ThisWorkbook.Sheets("Sheet1")

    'Set the range of cells to be protected (adjust the range as per your data)
    Set protectedRange = ws.Range("B2Big Grin10")

    'Protect the specified cells with a password
    ws.Protect Password:="mypassword", UserInterfaceOnly:=True
    protectedRange.Locked = True
End Sub

Explanation:

The code defines a subroutine named ProtectSpecificCells.
It declares variables for the worksheet (ws) and the range of cells to be protected (protectedRange).
Set ws = ThisWorkbook.Sheets("Sheet1") specifies the worksheet ("Sheet1") where the cells are located.
Set protectedRange = ws.Range("B2Big Grin10") sets the range of cells B2 to D10 to be protected.
The ws.Protect method is used to protect the entire worksheet with a password ("mypassword"). 
The UserInterfaceOnly:=True argument allows VBA code to modify protected cells without unprotecting the worksheet.
protectedRange.Locked = True locks the specified cells within the protected worksheet.