Exception HResult 0x800a03ec when trying to open Excel with Microsoft.Office.Interop.Excel.Workbooks.Open() - excel

Following Exception is thrown if I try to open an excel file on a client machine:
Exception from HRESULT: 0x800A03EC
Inner Exceptions: (empty)
Stack Trace:
at Microsoft.Office.Interop.Excel.Workbooks.Open(String Filename, Object UpdateLinks, Object ReadOnly, Object Format, Object Password, Object WriteResPassword, Object IgnoreReadOnlyRecommended, Object Origin, Object Delimiter, Object Editable, Object Notify, Object Converter, Object AddToMru, Object Local, Object CorruptLoad)
at (own assembly)
This HResult is a very generic Error, I could not find any useful informations by it.
My Setup:
WCF Service running inside a Windows Service. The exact same Setup is working on three other machines.
Things I can rule out:
Wrong Path
File does not exists
File is corrupt
File is write protected
Things I've done:
Created the Desktop folders as seen here (second Answer) https://social.msdn.microsoft.com/Forums/vstudio/en-US/4d6c383a-94eb-4898-9d22-aa4bb69be25b/
Gave the Desktop Folders "Everyone" or "Jeder" Permissions ("Jeder" is the equivalent of "Everyone" in German)
Started the Service with the currenlty active User
Changed the DCOM Config for Excel as advised by Heidi2 (see Link above)
Changed from Office 365 to Office Professional Plus
Locale is set to en-US while trying to open the file
Opened file manually which is supposed to be opened: no errors / warnings / user dialogs from excel
Installed English - US on target machine
Wrote an non WCF Service which starts the dll which executes the Interop request
Wrote an Console Application which starts the dll which executes the Interop request
Some Observations:
If I remove the Desktop folders (see my first "Things I've done"), I get the error as described and resolved here: Microsoft Office Excel cannot access the file 'c:\inetpub\wwwroot\Timesheet\App_Data\Template.xlsx'
Excel is open for a short time in the task manager while the dll tries to open the excel file
while I've had Office 365 installed, Office Click-Once Tasks opped up in Task Manager, sometimes freezing the Application. That's why I've switched to Professional Plus
If the active language is set to English US, this error is not thrown anymore; but images, which are supposed to be rendered by Interop, are rendered blank
What am I missing here?

Sorry - I know this is an indirect answer, although I would recommend you follow on. I personally have very bad experiences with Excel Interop services (ASP.NET application). As I am aware Microsoft does not recommend Interop server automation.
Even if you solve this issue you might stumble into issues with memory leakage, performance etc. In my previous project we were advanced with Excel interop automation until deployment. We stumbled into so many issues (Excel Interop processes not closing properly etc.) that we had to rewrite everything to OpenXML.
If possible use the new OpenXML format. There is a ClosedXML library that makes working with very easy.
Why OpenXML vs Interop?:
Efficiency (OpenXML is lightweight)
No memory leakage risk
Ease of use

Before trying this solution be sure that you read the "Things I've done" paragraph from the question (and tried what applies to you)
The Exception was thrown upon opening the Document; on the machine which generated the Excels, the files were generated invalid.
The solution was to change the Format of the numbers.
Go into System Configuration -> Time, Language and Region -> Language
Tap on the highlighted Hyperlink
Open Advanced Settings
Change the delimiter to a point "."

We have converted our Client / Server solution from 4GL language to C#, where embedded C# code below worked without any issue before, and started to receive same error message.
Excel.Application excelApp = new Excel.Application();
Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(fileExcel,
0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",
true, false, 0, true, false, false);
I have followed all the instructions in this thread, but to no avail, until I have realised that in our case at least fileExcel, which contains the full path with the name of the file and defined as System.String fileExcel had trailing spaces, e.g. instead of "C:\temp\MyTest.xls" it was "C:\temp\MyTest.xls[many many spaces]".
Once I have added Trim() to fileExcel as below, all went back to normal. Hope it will help to someone in the future.
Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(fileExcel.Trim(),
0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",
true, false, 0, true, false, false);

Related

How to stop from deleting a file/workbook in MS excel when it is already open?

We have designed Microsoft Addins for MS Excel and Word 2019 written in VB.net.
There we have designed a tab, on clicking this tab, we open a Task Pane.
On loading this task pane, we execute a code to launch another Excel File/Word file.
So when I delete a file in MS Word that is already open it shows an exception The file 'Filename' already exists.
Given below is the code snippet I am using to delete an already existing open file named processFile
My.Computer.FileSystem.DeleteFile(processFile)
Now when I run the same code snippet in MS Excel it does not show this exception and deletes the file.
I am not able to understand this behavior.
Kindly suggest if anyone has understanding on it
Here is some more information about which environment I'm working in:
Operating System : Microsoft Windows 10 Pro
Code Editor : Visual Studio 2019
Technology : Vb.net(.Net Framework 4.8)
MS Office Version : 2019(32 bit) : Microsoft Windows 10 Pro
The IOException should be thrown if the file is in use. You need to close any editors first and then delete files.
Check if the file is open. I have a code below that may help.
As import sfile use the fullpath with filename. (eg. "C:\Windows\test.txt")
returns True when file it's open and false when it isn't.
Yu will need "Imports System.IO"
Public Function IsFileInUse(sFile As String) As Boolean
Try
If File.Exists(sFile) Then
Using f As New IO.FileStream(sFile, FileMode.Open, FileAccess.ReadWrite, FileShare.None)
End Using
End If
Catch Ex As Exception
Return True
End Try
Return False
End Function
As per the information in the comment section, the file is opened in "protected mode" and you are saying that it is deleting while it is still open to the user.
So yes, if the file is engaged and deleted by some program, it should throw an exception and not delete. But if no exception is coming, i.e. some specific handling has been done by Windows/MS Excel so that file has been deleted while it is still kept on buffer and open. Its answer can be given by Microsoft only.
One solution, I can suggest is to close the "protected object" and then delete the file so that no file will be opened to the user and it will be safely deleted.
Snippet to open the file for Add-ins(VSTO):
Dim objProtectedMode As String objProtectedMode = Globals.Connect.Application.ProtectedViewWindows.Open(fileLocation, , False, False)
Snippet to delete the file safely:
If Not (objProtectedMode Is Nothing) Then
objProtectedMode.Close()
End If
My.Computer.FileSystem.DeleteFile(objProtectedMode)
Note: - Solution may vary for other add-ins. Code snippet provided for VSTO Add-ins.

Save Method of Application class failed when trying to save an Excel Document

I havea a method in Delphi that saves some data into a ExcelFile. The Program works fine for any kind of Excel except Excel 2013.
Here is the code
try
// If no instance of Word is running, try to Create a new Excel Object
ExcelApp := CreateOleObject('Excel.Application');
except
ShowMessage('Cannot start Excel/Excel not installed ?');
Exit;
end;
ExcelApp.DisplayAlerts := False;
ExcelApp.Workbooks.Add(xlWBatWorkSheet);
// fill the Excel file
ExcelApp.Visible := True;
// Save the Workbook
ExcelApp.save;
if not VarIsEmpty(ExcelApp) then begin
ExcelApp.DisplayAlerts := False; // Discard unsaved files....
ExcelApp.Quit;
end;
So As I said, this worked fine for Excel untill the 2013 Version. When I try to use this on a computer with Excel 2013 I get the error
Save Method of Application class failed.
Any Ideas why is this happening and any possible Workaround?
PS I tried with
ExcelApp.Workbooks[1].SaveAs('c:\test.xlsx', xlWBATWorksheet);
I also get an error :
SaveAS Method of Workbook class failed.
I also read that I could be that I don't have acces to save on that location, but i'm the administrator on the computer.
If I help the time of executing this operation takes a lot more time that It usually did in Excel 2010 or Excel 2007.
According to the documentation, the Excel Application object has no Save method. Use SaveAs from the Workbook object.
You are trying to save a file to the root directory of the system volume, and by default, that is secured so that standard user cannot create files in that location. Even though you are an administrator, UAC means that your process runs with a standard user token.
The other problem I see is that xlWBATWorksheet is not a file format constant. You mean to use xlOpenXMLWorkbook. This should be fine:
Workbook.SaveAs('c:\somedir\test.xlsx', xlOpenXMLWorkbook);
where you replace c:\somedir with some suitable path on your machine.
Switching to early bound COM might alleviate some of your travails but the answers can always be found in the documentation. You don't need to do this blind.
I haven't done any Microsoft Office automation myself but I do remember from the time that I still used Delphi 7 that when you installed it the installer actually asked you for which version of office do you wanna install the extensions for.
So I would gues that there are some differences in COM implementation that different versions of Microsoft Office use so it is posible that components your Delphi use for Microsoft Office Automation are not compatible with Office 2013.
May not be relevant but had same error message in VB6 (yes, 2016 and I still use it for odd things on Windows 10!) because the sheet was selected. Selected another object before saving and it worked.
You need to install KB2830391 HF460904 for Excel 2013 issue for AX 2009. Change in one sysExcel class on how the transfer/save are made!

Compatibility Between MS-Access 2003 and MS-Excel 2013

This is similar to a question that I've asked yesterday, but I've managed to find a fair bit more information: enough to warrant a new question, I feel.
My office has recently moved to Windows 7 along with Office 2013 - with the except of Access which has stayed as 2003.
Access works absolutely fine except when I try to automate Excel. This is a feature of nearly all my applications.
When I load an old project, the reference is automatically updated to "Microsoft Excel 15.0 Object Library" - it is held as an EXE file in Program Files (x86). Note: it does not say the reference is missing.
When I try to run any code which uses early binding, it fails with the following error message: "Error in loading DLL"
I've since tried late binding by doing the following:
Dim app As Object
Dim wb As Object
Set app = CreateObject("Excel.Application")
app.Visible = True
Set wb = app.Workbooks.Add
This creates the Application, it becomes visible, a Workbook is added, but then I get the following error: "Run-time error '1004':
Application-definted or object-defined error"
If I try to access VBA in the new Workbook I get the following error: "An error occurred initializing the VBA libraries (1004)" The Workbook is loaded in "Compatibility Mode"
The above leads me to believe that the 2 applications may not be compatable, but the following is worth considering:
If I try to use early binding I don't get the Intellisense drop-downs but words like Workbook and Worksheet do auto-capitalise themselves as you would normally expect them to. The code won't compile at all if I don't have the reference set, but it does compile - and throw and error - when it is. I've since tried Word 2013 - who's Object Reference is an OLB file rather than EXE - and I get the full Intellisense features I would except, but it still throws the same error when trying to run.
In a nut shell, does anyone know if I stand any chance of having the 2 work together?
Thanks

Send Excel file to printer in batch job

I will print excel file in a AX 2012 batchjob.
I chose this approach because the template is too complex to draw it in SSRS.
So, I already have a class which works with excel COM object without any problems on client. Then I created a similar class which runs on server. I used WinAPIServer instead of WinAPI, COM interopt, etc.
But now I've an error:
"workBooks" method is not supported by Automation Interface of COM-object "Excel.Application"
Note - AOS is installed on another machine.
Why is it happening?
Are there some special things in working with COM on AX-server side ?
I already tried to change properties of "Microsoft excel application" in different ways.

Excel Object SaveAs, error happens when Existing File is Open

Excel_Obj = CREATE OleObject
Excel_Obj.ConnectToNewObject( 'excel.application' )
Excel_Obj.Workbooks.Add
Excel_Obj.Application.ActiveWorkbook.WorkSheets.Add
Excel_Sheet = Excel_Obj.Application.ActiveWorkbook.WorkSheets[1]
//EXAMPLE
Excel_Sheet.Cells[1,1] = 45
Excel_Obj.Application.ActiveWorkbook.SaveAs(ls_file,56) //csv
//where ls_file = the Opened File
error happened after / during saveas.
try catch throw "error calling external object..in click..line.. saveas.."
--
i want to state to the user that the excel file is open therefore cannot be overwritten properly. I used a try catch and throwed a proper message but before the messagebox for the catch event happens, the PB execution error R0035 happens. any solutions or proper way to know if the excel file is open.
You might be able to check if the file is open first, have a look at this answer:
how to check if file is opened in excel using OLE (leaves excel process open)
I'd try a PowerScript FileOpen () call with a LockReadWrite! parameter to see if it can be opened, followed immediately by a FileClose () if it was successful. (I think this is a PowerScript-specific variation on the DXL solution Colin linked to.)
Good luck,
Terry
Have you tried approaches similar to these?
Using Win32 API:
http://www.rgagnon.com/pbdetails/pb-0030.html
Using PB function fileopen()with the (default) exclusive rights set:
http://www.tek-tips.com/viewthread.cfm?qid=1610670
In other words, see if the file can be opened exclusively before connecting to Excel or making the CSV?
You will have to turn off the option to break into the debugger for that exception to see the exception handling work in the IDE. Look for the Help topic "Exception Settings dialog box" for details. Once you see it's working I recommend you set it back to break into the debugger, since you'd normally want to see what threw the error.
You cannot use ole when document is open( even you set lock write) by the user and not by apllication.
my approach, I have been using many times till now:
Check excel is open or not, use use can use api or wsh script in the internet to check app opened. If opened do not run save as and tell user to close excel and not run it for while for while.
if you user run excel and your program still running active workbook and worksheet application will be switch to excel that opened by user ( imagine it wrong written data).
Change your code as below
if Excel_Obj.ConnectToNewObject( 'excel.application' ) <> 0 then
messagebox("warning", "could connect to excel", stopsign!)
RETURN
end if
just for knowledge another technique is DDE call, but not common today and most complicated.
Happy coding From pb developer.

Resources