Home » excel » Lock rows in Excel using VBA

Lock rows in Excel using VBA

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have an Excel sheet with columns A to F to be filled out by different users. Once one row is completed another user (control user) enteres “done” in column G. As soon as the user entered “done” in coulmn G, I want a VBA script to lock the entire row (column A to G) so that no one can change any of that row entries any longer. Is that possible using VBA scripting?

How to&Answers:

We must start with all cells un-protected and the sheet Locked

Enter the following Event macro in the worksheet code area:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim N As Long
    N = Target.Row
    If Intersect(Target, Range("G:G")) Is Nothing Then Exit Sub
    If Target.Text <> "Done" Then Exit Sub
    ActiveSheet.Unprotect
      Range("A" & N & ":G" & N).Locked = True
    ActiveSheet.Protect
End Sub

Because it is worksheet code, it is very easy to install and automatic to use:

  1. right-click the tab name near the bottom of the Excel window
  2. select View Code – this brings up a VBE window
  3. paste the stuff in and close the VBE window

If you have any concerns, first try it on a trial worksheet.

If you save the workbook, the macro will be saved with it.
If you are using a version of Excel later then 2003, you must save
the file as .xlsm rather than .xlsx

To remove the macro:

  1. bring up the VBE windows as above
  2. clear the code out
  3. close the VBE window

To learn more about macros in general, see:

http://www.mvps.org/dmcritchie/excel/getstarted.htm

and

http://msdn.microsoft.com/en-us/library/ee814735(v=office.14).aspx

To learn more about Event Macros (worksheet code), see:

http://www.mvps.org/dmcritchie/excel/event.htm

Macros must be enabled for this to work!