title: Excel Automation: Protect single worksheet from deletion by user
body: <p><strong>VSTO 4.0 / Office 2007</strong></p>
  
  <p>In an Excel document-level automation project, I have a worksheet that <strong>must not be deleted from the workbook</strong>. I am afraid that a careless user might delete it by accident, which currently causes a lot of grief (exceptions galore).</p>
  
  <p>I can not protect the entire workbook, because the user must be able to create, delete and otherwise modify this file. Exactly <em>one sheet</em> needs to be protected from deletion, but I may be overlooking something, so if there exists such solution I'm all ears. For example I could imagine that I can <code>Protect()</code> and <code>Unprotect()</code> the workbook when the sheet is visible, but this solution seems messy.</p>
  
  <p>Googling <a href="http://www.excelforum.com/excel-programming/401664-prevent-sheet-deletion.html" rel="nofollow noreferrer">yielded</a> the following VBA code:</p>
  
  <pre><code>Private Sub Worksheet_Activate()
  Dim CB As CommandBar
  Dim Ctrl As CommandBarControl
  For Each CB In Application.CommandBars
  Set Ctrl = CB.FindControl(ID:=847, recursive:=True)
  If Not Ctrl Is Nothing Then
  Ctrl.OnAction = "RefuseToDelete"
  Ctrl.State = msoButtonUp
  End If
  Next
  End Sub
  </code></pre>
  
  <p>I'm not familiar with VBA, but I tried running this from the VSTO generated startup method:</p>
  
  <pre><code>private void Sheet1_Startup(object sender, System.EventArgs e)
  {
      //Is there a neater way to iterate through all Office Collections?
      for (var i = 1; i &lt;= Application.CommandBars.Count; i++)
      {
          var commandBar = Application.CommandBars[i];
          //847 is a magical constant that any fule no has something to do with sheet deletion
          var control = commandBar.FindControl(Id: 847, Recursive: true);
          if (control != null) control.OnAction = null;
      }
  }
  </code></pre>
  
  <p>This code seems to do exactly nothing. You may ask <em>"Hey, Gleno, why are you setting <code>OnAction</code> to null"</em> , well I don't know what to set it to... The linked VBA solution attaches to Activate and Deactivate events, so there's more code where that came from. </p>
  
  <p>Thanks in advance.</p>