I am managing an Excel VSTO add-in that works on specific files and does not support inserting/deleting columns.
I would like to prevent the user from being able to do so in order to secure data in the files.
- I tried to Protect() sheets through C#, however it only locks column insertion/deletion if you also lock the content, which I cannot do
- I tried using AppEvents and more specifically SheetChange, but haven't found a way to cancel the change. I believe there is none but let me know if I'm wrong
- I am aware that an Undo package exists somewhere but haven't looked whether it works with events because:
- I would prefer to avoid external packages
Undo()
in my situation would trigger-chainSheetChange
which obviously doesn't work without adding extra complexity
Is there a way to prevent column insertion/deletion in Excel sheets, through C# specifically, without locking anything else and if possible in a simple manner?
Thanks.
EDIT - UPDATE
I have been setting up a makeshift solution so far which I'll share here:
AppEvents_SheetChangeEventHandler EventSheetChangeHwnd;
private void ThisAddin_Startup(object sender, EventArgs e)
{
Application.SheetChange -= EventSheetChangeHwnd;
EventSheetChangeHwnd = new AppEvents_SheetChangeEventHandler(SheetChange_Event);
Application.SheetChange += EventSheetChangeHwnd;
}
private void SheetChange_Event(Object Sh, Range Target)
{
if(!Target.Address.Equals(Target.EntireColumn.Address)) // Can use Target.Row != 1 too to check faster and remove unwanted occurences
return;
Application.EnableEvents = false; // Prevents event from re-firing after undo
Application.Undo(); // Native undo method
Application.EnableEvents = true;
}
Now this isn't a proper solution because:
- The event fires every time a value is changed in the sheet, if you're writing data cell by cell it will fire every time and can get to a point where you see a drop in processing speed
- It will fire if a whole sheet or a whole column is copy pasted - basically it doesn't check specifically for column insertion/deletion
- Having to use
Application.EnableEvents
could have side effects and actually requires more code to handle properly