Creating a Name Range in Excel using NetOffice throws a COMException - c#

I would like to create a Named Range in Excel from a NetOffice, but I cannot figure out how to invoke the method. Whatever the input, the underlying Excel Object throws a COMException with a generic HRESULT 0x800A03EC Error.
Excel version Office 365, 16.0.13001, 64 bits
NetOfficeFw package, version 1.7.4.11
I have no hint about what is wrong (syntax? Excel version? NetOffice version?).Is there a known bug on this method?
Thanks for your help!
private void CreateNameRange(Workbook wb, Range range)
{
try
{
Name existingName = (Name)wb.Names.FirstOrDefault(); //works fine if a name already exists in Excel
wb.Names.Add(); //throws
wb.Names.Add("name1"); //throws
wb.Names.Add("name1", range); //throws
wb.Names.Add("name1", range.Address); //throws
wb.Names.Add("name1", "F7"); //throws
wb.Names.Add("myName", "=Sheet1!$F$7:$I$13"); //throws
wb.Names.Add("myName", "'=Sheet1!$F$7:$I$13'"); //throws
if (_wb.ActiveSheet is Worksheet ws) {
ws.Names.Add("myname", "=Sheet1!$F$7:$I$13"); //throws as well
}
}
catch (COMException e)
{
//always ends up here with Inner Exception : COMException (HRESULT 0x800A03EC)
}
}

Actually, the root cause of this issue was not the method itself, but when the method was called.
I was trying to create Named Ranges from within a UDF Function but Excel considers this operation as unauthorized, along with other worksheet/data manipulation when calculation is being made, and that's why the COM Exception was raised.
Bottom line : Named Ranges cannot be created when a workbook calculation is in progress.

Related

C# Excel Number Format error

I'm having troubles setting columns format in Excel with Interop. I'm using C#, below is the code:
Excelop.Range rg = (Excelop.Range)wb.Worksheets[1].Cells[1, i];
rg.NumberFormat = "#"; //Exception is raised here
I get the below exception when compiled:
"An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll
Additional information: Unable to set the NumberFormat property of the Range class"
Appreciate your support.
My guess is that your worksheet is protected.
You likely need to do something like:
wb.Worksheets[1].Unprotect (Password:"your_password")
These may be of assistance:
https://www.mrexcel.com/forum/excel-questions/449829-run-time-error-1004-unable-set-numberformat-property-range-class.html
"Unable to set the NumberFormat property of the Range class"

Trying to access excel COM object as admin user

The objective is to access the running Excel workbook in the machine. Intention is to close the respective workbook though this application which was opened by the user.
Achieved: I used the following code snippet to access the Excel COM object
Excel.Application instance = null;
try
{
instance = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
}
catch (Exception ex)//Excel not open
{
wasFoundRunning = false;
}
if (wasFoundRunning)
{
foreach (Excel.Workbook ss in instance.Workbooks)
{
string s = ss.Name;
}
}
Issue: Above code works only if the excel sheet and the application opened by the same user in the machine. I have to run the application as administrator and it fails. Exception as follows and it means that it cannot find any excel sheet running.
Exception: Operation unavailable (Exception from HRESULT: 0x800401E3 (MK_E_UNAVAILABLE))
It fails if I run my application elevated and user opens the sheet.
Any ideas to fix this?

Excel C# interop worksheet delete

I have an app using Excel COM interop. It copies a template XLS to an existing doc, replacing same-named tabs by Delete old then Copy new from template.
I am getting 800A03ec exception when my app tries to delete a worksheet.
This problem is in code that has been working for years but now fails after an upgrade to Office 2016.
I find that if I set app.Visible = true, the operation completes properly! But I do not want Excel visible.
If app.Visible = false, I do not get an error from the first worksheet Delete(), but exception occurs on the second.
The first delete of the last tab seems to go OK, but 'Sheets' array of the worksheets object doesn't decrease as I would expect. However the corresponding Sheet item in the array becomes a "null" worksheet.
The second delete, of the tab before it, throws an exception on delete.
I have thoroughly ensured:
No COM reference leaks
All COM references are discarded before each delete, except for the worksheet to be deleted and its parent app, etc. objects
DisplayAlerts is false
Worksheets are simple and ordinary, nothing hidden etc.
Why would it work when app is visible, but not work when app is hidden??
UPDATE: code fragment
int _DeleteTargetTab(string tabName)
{
List<object> comRefs = new List<object>();
int prevTabIndex;
int tabToDelete = _FindTargetTemplateIndex(tabName, out prevTabIndex);
if (tabToDelete > 0)
{
try
{
Excel.Sheets targetSheets = _workbook.Sheets;
comRefs.Add(targetSheets);
Excel.Worksheet targetWorksheet = targetSheets[tabToDelete];
comRefs.Add(targetWorksheet);
targetWorksheet.Delete();
}
finally
{
ExcelUtility.ReleaseAll(comRefs);
}
}
return prevTabIndex;
}
and ExcelUtility.ReleaseAll() calls Marshal.ReleaseComObject(), then GC.Collect() and GC.WaitForPendingFinalizers().
Target worksheet has 8 tabs. Last tab is deleted, then copied, without exception. Then on tab 7 delete throws an exception, only when app is hidden. Works fine on older Office.
Copy code is
void _CopyTemplateTabToTarget(Excel.Worksheet templateWorksheet, int prevTargetTabIndex)
{
List<object> comRefs = new List<object>();
try
{
Excel.Sheets targetSheets = _workbook.Sheets;
comRefs.Add(targetSheets);
Excel.Worksheet prevSheet = targetSheets[prevTargetTabIndex];
comRefs.Add(prevSheet);
templateWorksheet.Copy(Type.Missing, prevSheet);
}
finally
{
ExcelUtility.ReleaseAll(comRefs);
}
}
Init code is
_app = new Excel.Application();
_app.DisplayAlerts = false;
_app.Visible = false;
I got further by adding this:
//
// Super important to activate a tab other than what needs to be deleted.
// Cast is required because an event and method have the same name "Activate".
//
((Excel._Worksheet)_weeklyDataSheet).Activate();
Then that got me to some code around my apps' Save function that used to work but was throwing exception:
_weeklyDataSheet.Select(Type.Missing);
I changed that to Activate() as well and made more progress. But yet Excel still threw exception on Delete() this time on the third workbook.
I was forced to run app Visible for the week's report. But even that ran through about 80 workbooks and then Excel locked up, mouse cursor rapidly flashing between arrow and wait timer animation, and my app got RPC error eventually.
Conclusion: ABANDON COM APIS for Office 2016. Microsoft seems not to support them properly anymore.

C#, EPPLUS - cannot save_as excel another time

we just have a excelpackage object given, which was saved using SAVEAS(file) correctly. But when I try to save_as another time (after re-arranging worksheets), then it will be thrown this exception:
An unhandled exception of type 'System.InvalidOperationException'
occurred in EPPlus.dll
Error saving file (report.xlsx)
Already using the latest version 4.0.5 EPPLUS.
Also tried the other post without luck:
var reportFileInfo = new FileInfo(reportFile);
if (reportFileInfo.Exists)
reportFileInfo.Delete();
ExcelReportStream.SetLength(0);
ExcelReport.Stream.Position = 0;
ExcelReport.Stream.CopyTo(ExcelReportStream);
using (var excelToSave = new ExcelPackage())
{
excelToSave.Load(ExcelReportStream);
excelToSave.SaveAs(reportFileInfo); <<<<< EXCEPTION again!
}
An unhandled exception of type 'System.InvalidOperationException'
occurred in EPPlus.dll
Error saving file (report.xlsx)
The ExcelPackage is a property and with the first try, it will be ExcelPackage.SaveAs(reportFile) works on first time. But not on second.
No further information from the compiler...
Any ideas?
Thank you.

Excel AddIn : Hide a datafield in a pivottable

I'm trying to control an Excel (2010) PivotTable from a VSTO (excel AddIn) in C# (4.0). I've got no problem adding PivotFields (Dimensions) and DataFields (Measures) to the PivotTable.
The problem is I can't remove a DataField.
My DataField is a PivotField object.
I've tried :
myDataField.Hidden = true;
myDataField.DisplayInReport = false;
myDataField.Orientation = XlPivotFieldOrientation.xlHidden;
// This last one is what I use to remove a (Dimension) PivotField
Every one of these lines throws a COM Exception with absolutely no information in it. The only thing I have is the message : "Exception de HRESULT : 0x800A03EC", which seems to be common to every VSTO exception.
If anyone has a solution, that would help me a lot.

Categories

Resources