Home > Enterprise >  System.Runtime.InteropServices.InvalidComObjectException: when trying to write to Excel Cell with Mi
System.Runtime.InteropServices.InvalidComObjectException: when trying to write to Excel Cell with Mi

Time:04-29

I am trying to write my class property value to an Excel cell with Microsoft.Office.Interop.Excel but get the following error: System.Runtime.InteropServices.InvalidComObjectException

Here is my code:

...

private Microsoft.Office.Interop.Excel.Application xlapp = new Microsoft.Office.Interop.Excel.Application();

...

//open excel file
Workbook wbAngebot = xlapp.Workbooks.Open(abs);  //abs = absolute path to file

//assign worksheet           
Worksheet wsAngebotsinfo = wbAngebot.Worksheets["Angebotsinformation"];

//write value to cell
wsAngebotsinfo.Cells[1,1] = AnredeVerk; //--> causes the exception, AnredeVerk is a string property

Is it possible that AskToUpdateLinks or ScreenUpdating or Visible xlapp-properties are causing the error when they are set to false? I have also tried wsAngebotsinfo.Range["A1"].Value and Value2 but same error occurs. Any ideas why this is happening?

CodePudding user response:

This is how I set cell values using excel interop.

// Get the range object that represents the cell
//
var cell = (Range)worksheet.Cells[row, col];

// Set the cell value
//
cell.Value = value;

// Release the com object
//
Marshal.ReleaseComObject(cell);

It is important to remember to release all objects you access.

  • Related