It needs a minor tweak to become "protect/unprotect." I assumed that if a cell is not empty, you only want to lock or safeguard it.
Option Explicit
Sub lockcells()
Dim Rng As Range
Dim MyCell As Object
Set Rng = Range("A1:D20") 'Set range to lock cells
If ActiveSheet.ProtectContents = True Then 'Check if sheet is protected
ActiveSheet.Unprotect Password:="123" 'Password to unprotect
Else
For Each MyCell In Rng
If MyCell.Value <> "" Then 'If cell is empty, if not empty lock the cell
MyCell.Locked = True 'Lock cell
MyCell.FormulaHidden = False 'Don't hide formulas
End If
Next MyCell
ActiveSheet.Protect Password:="123", UserInterFaceOnly:=True 'Protect Sheet
End If
End Sub
If you want all cells to be editable except a range you can add the following code:
'Else
ActiveSheet.Cells.Locked = False
ActiveSheet.Cells.FormulaHidden = False
'For Each MyCell In Rng