Lock or Unlock Cells in Excel Add-in with code example

Lock or Unlock Cells in Excel Add-in with code example

Lock

Protect entire workbook, but you want to allow user to some cells, the lock cells feature make it happens. Before you protect workbook or sheet, you should unlock cells which you would like user to be available for editing.

Steps

  • Select cells which you would like to lock
  • Right click and from popup command list select Format cells, or you can hit CTRL + 1 key from keyboard as short hand and a popup will appear having following tabs:
    • Number
    • Alignment
    • Font
    • Border
    • Fill
    • Protection

Select protection tab, point to be noticed here : If you try these steps on a workbook or worksheet you haven’t protected, you’ll see the cells are already locked.

Now click on the Review tab in the ribbon, in the Changes group, select either Protect Sheet or Protect Workbook, and then reapply protection. Let’s write some code to achieve the same:

VBA code example

Public Sub LockCellsExample()
	'Declare Rane object
	Dim oRange as Range
	
	'Bind selection
	Set oRange=Selection
	
	'Unlock cells
	oRange.Cells.Locked=False
	
	'Protect sheet
	ActiveSheet.Protect "12345"
	
	'Cleanup
	Set oRange = Nothing
End Sub

C# code example

private void btnLockCell_Click(object sender, RibbonControlEventArgs e)
{
	//retain active row selection
	excel.Range oRange = Globals.ThisAddIn.Application.Selection;
	//Performing locking
	oRange.Cells.Locked = false;
	//build sheet object using parent method
	excel.Worksheet oSheet = oRange.Parent;
	//protect sheet
	oSheet.Protect("12345");
}

Let’s see output of above code step by step when we run it. Also, I have used one more trick where I build sheet object from Parent property of Range object so please do not confuse.

Step 1: make selection to your range

Step 2: run the code and right click over selected range to see actual locking is done or not:

If you notice in the right click popup menu mostly commands are disabled which shows you made a right move. Now to test try to edit any cells which you highlighted during Lock operation the Excel will allow you but if you try to make changes in other area you will not be able to do.

Next >> Create Live Clock using Excel VBA

Leave a Reply

Your email address will not be published. Required fields are marked *