Excel interop - Unable to find the Add property of the Sheets class
Here’s a refined version of your query with improved grammar and clarity:
I am developing an Excel plugin in C# using Add-in Express. The plugin displays a menu item called "CreateSheet."
When the user opens Excel and selects a blank workbook, there is a default sheet named "Sheet1." If the user clicks the "CreateSheet" menu item without first selecting the default sheet, the following line of code throws a COM exception stating that the Add method is not available for the sheet object:
Excel.Worksheet xlNewWorkSheet = (Excel.Worksheet)ExcelApp.Worksheets.Add(
Type.Missing,
ExcelApp.Worksheets[ExcelApp.Worksheets.Count],
Type.Missing,
Type.Missing
);
However, if the user first clicks somewhere in the default sheet ("Sheet1") and then clicks the "CreateSheet" menu item, the new sheet is added successfully without any exception.
How can I modify the code to ensure the new sheet is added reliably, even if no cell is selected in the default sheet?
Below is the exception seen.
I tried to activate the workbook, sheet1, but nothing works.