Search code examples
c#excelnetoffice

Excel User Defined Function Locks Invoking Spreadsheet


I am using NetOffice to edit an Excel Spreadsheet. If I call the code from an Excel user defined function it will not let me edit the invoking spreadsheet.

Excel.Application excelApplication = Excel.Application.GetActiveInstance();
Excel.Worksheet workSheet = (Excel.Worksheet) excelApplication.ActiveSheet;
Excel.Range cell = workSheet.Cells[2, 2];

object value = cell.Value; //works
cell.Value = 3; //Throws Exception

is there a workaround that will enable me to do this?

The exception is

"System.Runtime.InteropServices.COMException (0x80004005): See inner exception(s) for details. ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Runtime.InteropServices.COMException: Exception from HRESULT: 0x800A03EC --- End of inner exception stack trace --- at System.RuntimeType.InvokeDispMethod(String name, BindingFlags invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers, Int32 culture, String[] namedParameters) at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams) at System.Type.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, CultureInfo culture) at NetOffice.Invoker.PropertySet(COMObject comObject, String name, Object[] value) at NetOffice.Invoker.PropertySet(COMObject comObject, String name, Object[] value) at NetOffice.ExcelApi.Range.set_Value(Object value) at ExcelExamplesCS45.Example01.RunExample() in \psf\home\Documents\Visual Studio 2013\Projects\Excel-REPL\Excel-REPL\Example01.cs:line 29 at ClojureExcel.MainClass.Test() in \psf\home\Documents\Visual Studio 2013\Projects\Excel-REPL\Excel-REPL\MainClass.cs:line 310"


Solution

  • There is a very simple workaround: simply edit the worksheet in a separate thread. Why didn't I think of it to begin with!!???