Excel – VBA code to lock only user selected (Highlighted) cells in excel

excelvba

I was wondering how can i one use VBA/macros to lock certain excel cells that are selected/highlighted by the user.

The code im using right now is locking the entire sheet.

Sub Macro4()
'
' Macro4 Macro
'

'
  Worksheets("Sheet1").Activate
  ActiveSheet.Unprotect
Cells.Select
Selection.Locked = True
ActiveSheet.Protect
End Sub

Any ideas on what im doing wrong?

Thank you for your time.

Best Answer

If you want to perform any actions on the selected cell(s) every time a new selection occurs, you should rely on the code being triggered when this happens:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

  Selection.Locked = True

End Sub

This inside the file with the code for the given sheet; that is, if you want to consider Sheet1, the file where you have to write this code is: Microsoft Excel Objects/Sheet1 (Sheet1).

UPDATE AFTER YOUR COMMENT

Sub Button1_Click()
      Selection.Locked = True
End Sub

This code locks all the cells selected when the Button1 is clicked.