title: C# Excel Add in : Make worksheet read only but editable through code
body: <p>I have created an Excel add-in in C#, In my add-in I have a form that retrieves data from web service and writes it to excel, I want  to make the excel sheet read only, but I also want to edit it from behind the code.</p>
  
  <p><strong>What i want to do:</strong></p>
  
  <p>Basically I want to block user from accessing the worksheet, he can only make changes through the form that I have created.</p>
  
  <p>I tried:</p>
  
  <p><strong>1</strong>- To add cell validation to forbid any changes to the cell but it still allows other operations on sheet such as delete rows columns etc.</p>
  
  <p><strong>2</strong>- To protect worksheet using a password like this.</p>
  
  <pre><code>var activeWorksheet = ((Excel.Worksheet)Globals.ThisAddIn.Application.ActiveSheet);
  activeWorksheet.Protect("password");
  </code></pre>
  
  <p>But the above will not let me edit the worksheet through code, I have to unlock the worksheet whenever i want to make changes ie.</p>
  
  <pre><code>activeWorksheet.Unprotect("password");
  // Do some changes.
  activeWorksheet.Protect("password");
  </code></pre>
  
  <p>This way worksheet will stay unprotected while my Edit code is running (it may consume some time as there may be thousands or more records in sheet).</p>
  
  <p>I can think of one way is to unlock invidual cells to edit them and lock them again, I tried the below code but its not working:</p>
  
  <pre><code>var cellToEdit = activeWorksheet.Range["A2"];
  activeWorksheet.Protection.AllowEditRanges.Add("A1",cellToEdit , "password");
  cellToEdit.value = "changed cell";
  </code></pre>
  
  <p>Please suggest me some solution.</p>