07-27-2023, 10:39 AM
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("B210")
'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("B210") 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.
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("B210")
'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("B210") 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.