Check sheet protection in Excel Addin C#

Check sheet protection in Excel Addin C#

Protection:

Allows user to protect data against unwanted changes from others. Excel C# offers Protect method which helps protecting sheet by supplying desired password. In this article we will see how to perform check if Sheet is already protected or not. If sheet is not protected we will set password to Protect method and make sheet protection enabled.

Prerequisites:

  • Visual Studio 2015 or above having Microsoft Office for Developer Tool installed
  • Create Excel Addin in C# code style (Visual Studio Tools for Office)
  • Create a ribbon designer and put button

Code example:

private void btnProtectSheet_Click(object sender, RibbonControlEventArgs e)
{
	//get reference of active worksheet
	excel.Worksheet oWorksheet = Globals.ThisAddIn.Application.ActiveWorkbook.ActiveSheet;
	//check if sheet is already prtected
	if (oWorksheet.ProtectContents==false)
	{
		//Protect sheet
		oWorksheet.Protect("12345");
	}
}

Output:

To unprotect sheet you need to call Unprotect method following password as parameter:

private void btnProtectSheet_Click(object sender, RibbonControlEventArgs e)
{
	//get reference of active worksheet
	excel.Worksheet oWorksheet = Globals.ThisAddIn.Application.ActiveWorkbook.ActiveSheet;
	//check if sheet is already prtected
	if (oWorksheet.ProtectContents==false)
	{
		//Protect sheet
		oWorksheet.Protect("12345");
	}
	else
	{
		//Unprotect sheet
		oWorksheet.Unprotect("12345");
	}
}

Next : Lock or Unlock cells in Excel using C#

Leave a Reply

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