How to lock a row with VBA

Mootastic

New Member
Joined
Apr 13, 2011
Messages
2
I am having difficulty figuring out how to lock a row using VBA code. I know I can unlock the entire document, lock a single row and then protect sheet, but doing it that way does not allow me to open and collapse groups without first unlocking the document. So I am looking for help on a VBA code that would let me lock a single row. I have looked around for information on this for awhile, and I came across this...

Private Sub Worksheet_change(ByVal Target As Excel.Range)
If Target.Address <> "$A$1" Then If Target.Address <> "$B$1" Then Exit Sub
Application.EnableEvents = False
MsgBox "Error, incorrect operation.", 48, "Sorry, I'm protected."
Application.Undo
Application.EnableEvents = True
End Sub

That lets me block single cells, and I can technically go on with that to block a row, but I will need to be able to add a new row to be locked occasionally and I would rather not have to go through a long process of editing the 1's to 2's and so on. Any help would be appreciated.
 

Excel Facts

Shade all formula cells
To shade all formula cells: Home, Find & Select, Formulas to select all formulas. Then apply a light fill color.
Locking cells [or rows] is only operational if a worksheet is protected. That is just the way Excel works.

If you want different behavior, you'll need to write code for it [similar to what you posted]. If you need to 'lock' other rows in the future, you could adapt the code you showed to accept a range input parameter [the row to be 'locked'].
 
Upvote 0
Did this ever get solved? I'd like to do essentially the same thing. I just want to protect the first row (header of a table) of ever worksheet.
 
Upvote 0

Forum statistics

Threads
1,224,607
Messages
6,179,871
Members
452,948
Latest member
UsmanAli786

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top