.Net Interop Excel ExportAsFixedFormat() Exception HResult: 0x800A03EC - vb.net

I'm currently implementing a method that generated multiple sheets and export them as PDF. For this I'm using the Microsoft.Office.Interop Library (v14.0.0.0) with .NET 4.5.2 . Running Office is 2016
My code:
Dim excel As New Application()
excel.Visible = False
excel.DisplayAlerts = False
Dim workbooks As Workbooks
workbooks = excel.Workbooks
Dim workbook As Workbook = workbooks.Add(Type.Missing)
[...]
workbook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, String.Format(<a Path>)
ReleaseComObject(workSheet)
workbook.Close()
ReleaseComObject(workbook)
excel.Quit()
ReleaseComObject(excel)
The ReleaseComObject() looks like this (according to Microsoft Support):
Private Sub ReleaseComObject(objectToRelease As Object)
While System.Runtime.InteropServices.Marshal.ReleaseComObject(objectToRelease) > 0
End While
objectToRelease = Nothing
End Sub
This works fine if I run this code for one iteration BUT I noticed that the EXCEL-Process is still running.
If I try to do this in batch-mode (in the meaning of a for-loop) I get an excetion when entering the 2nd interation:
System.Runtime.InteropServices.COMException (0x800A03EC): Ausnahme von HRESULT: 0x800A03EC
bei Microsoft.Office.Interop.Excel.WorkbookClass.ExportAsFixedFormat(XlFixedFormatType Type, Object Filename, Object Quality, Object IncludeDocProperties, Object IgnorePrintAreas, Object From, Object To, Object OpenAfterPublish, Object FixedFormatExtClassPtr)
bei Controller.CreateListing(DataTable data, Int32 year, String mandantShortName) in ...
Line that throws exception:
workbook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, String.Format(<a Path>)
For reseach/testing I debugged before reentering the loop and killed the excel-process but w/o any changes.
Anyone faced this problem as well? Solutions/Suggestions?

In order to address the issue with Excel not closing properly replace:
Private Sub ReleaseComObject(objectToRelease As Object)
While System.Runtime.InteropServices.Marshal.ReleaseComObject(objectToRelease) > 0
End While
objectToRelease = Nothing
End Sub
With this bit of code as illustrated by Siddharth Rout:
Private Sub ReleaseObject(ByVal obj As Object)
Try
Dim intRel As Integer = 0
Do
intRel = System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
Loop While intRel > 0
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
You could use your While statement instead of the Do statement but I feel it reads better this way. The important bit here is GC.Collect().
You also have to make sure you release in the right order and release everything. This is usually in backwards order. So in your case, start off with the workSheet then the workbook then workbooks and then lastly excel:
ReleaseObject(workSheet)
workbook.Close()
ReleaseObject(workbook)
ReleaseObject(workbooks)
excel.Quit()
ReleaseObject(excel)
This is the code I put together to test:
Dim app As New Excel.Application()
app.Visible = False
app.DisplayAlerts = False
Dim wbs As Excel.Workbooks = app.Workbooks
Dim wb As Excel.Workbook = wbs.Add()
Dim ws As Excel.Worksheet = CType(wb.Sheets(1), Excel.Worksheet)
ReleaseObject(ws)
wb.Close()
ReleaseObject(wb)
ReleaseObject(wbs)
app.Quit()
ReleaseObject(app)
The process starts and once ReleaseObject(app) has been called the process then closes.

I just figured it out what the problem caused (own Bug).
But it still leaves the question open, why the Excel-Proccess ain't closing.

Try to run application or service as administration account. This solved my problem.

Related

Excel vba, Opening new Application: Microsoft Excel is waiting for another application to complete an OLE action

I have the following vba code. It creates new Excel application and uses it to open a file. Then it MsgBoxes some cell's value in this file.
Sub TestInvis()
Dim ExcelApp As Object
Set ExcelApp = CreateObject("Excel.Application")
Dim WB As Workbook
Set WB = ExcelApp.Application.Workbooks.Open("Y:\vba\test_reserves\test_data\0503317-3_FO_001-2582480.XLS")
Dim title As String
title = WB.Worksheets(1).Cells(5, 4).Value
MsgBox (title)
WB.Save
WB.Close
ExcelApp.Quit
Set ExcelApp = Nothing
End Sub
The problem is that after MsgBoxing it slows down and eventually gives a Microsoft Excel is waiting for another application to complete an OLE action window. Why does it do this? It's not like there are any hard commands being implemented. And how should I deal with it?
This happens because the Excel instance in ExcelApp is waiting for User Input, most likely.
You can try to add ExcelApp.DisplayAlerts = False to skip any pop-ups that might be there.
Also, while troubleshooting add the line ExcelApp.Visible = True so you can see what's going on in the second instance and troubleshoot there.
I encountered this problem in the following situations:
An alert was opened by the Application Instance and it was awaiting user input.
While opening a file, it was coming up with some message about a crash when the file was previously opened and whether I wanted to open the saved version or the in memory version (although this should happen before the msgBox)
If you run the code multiple times and it crashes, it might have the file open as read only since there's another hidden instance of Excel that locked it (check your task manager for other Excel processes)
Rest assured that in any case the problem is not with your code itself - It runs fine here.
Code that works for me.
You can select the file from FileDialog. In comments You have code that close the workbook without saving changes. Hope it helps.
Option Explicit
Sub Import(Control As IRibbonControl)
Dim fPath As Variant
Dim WB As Workbook
Dim CW As Workbook
On Error GoTo ErrorHandl
Set CW = Application.ActiveWorkbook
fPath = Application.GetOpenFilename(FileFilter:="Excel file, *.xl; *.xlsx; *.xlsm; *.xlsb; *.xlam; *.xltx; *.xls; *.xlt ", Title:="Choose file You want to openn")
If fPath = False Then Exit Sub
Application.ScreenUpdating = False
Set WB = Workbooks.Open(FileName:=fPath, UpdateLinks:=0, IgnoreReadOnlyRecommended:=True)
Set WB = ActiveWorkbook
MsgBox("File was opened.")
'Application.DisplayAlerts = False
'WB.Close SaveChanges:=False
'Application.DisplayAlerts = True
'MsgBox ("File was closed")
Exit Sub
ErrorHandl:
MsgBox ("Error occured. It is probable that the file that You want to open is already opened.")
Exit Sub
End Sub
None of these methods worked for me. I was calling a DLL for MATLAB from VBA and a long simulation would pop up that Excel was waiting on another application OLE action, requiring me to click it off for the routine to continue, sometimes quite a few times. Finally this code worked (saved in a new module): https://techisours.com/microsoft-excel-is-waiting-for-another-application-to-complete-an-ole-action/
The way I used it is a little tricky, as the directions don't tell you (here and elsewhere) which causes various VBA errors, so I add to the description for what works in Excel 365:
Create a new module called "ToggleOLEWarning" (or in any new module, important!) which only contains the following code:
Private Declare Function CoRegisterMessageFilter Lib "ole32" (ByVal IFilterIn As Long, ByRef PreviousFilter) As Long
Public Sub KillOLEWaitMsg()
Dim IMsgFilter As Long
CoRegisterMessageFilter 0&, IMsgFilter
End Sub
Public Sub RestoreOLEwaitMsg()
Dim IMsgFilter As Long
CoRegisterMessageFilter IMsgFilter, IMsgFilter
End Sub
Then in your main function, just decorate the long running OLE action with a couple lines:
Call KillOLEWaitMsg
'call your OLE function here'
Call RestoreOLEwaitMsg
And it finally worked. Hope I can save someone the hour or two it took for me to get it working on my project.

How To Develop My Own Excel Add-in in VB.Net

I am trying to create an Excel Add-in using Vb.Net. I've started an Excel 2007 Add-in Project in VS2010. Sadly, I am not good with vb.net; I am more a VB6 developer in this regard, and my ThisAddin.vb code is:
Public Class ThisAddin
Private Sub ThisAddIn_Startup() Handles Me.Startup
End Sub
Private Sub ThisAddIn_Shutdown() Handles Me.Shutdown
End Sub
' test function; simple
Public Function getRowCount() As Long
Dim thisWB As Workbook = Me.Application.ThisWorkbook
Dim activWS As Worksheet
activWS = thisWB.ActiveSheet
Return activWS.UsedRange.Rows.Count
End Function
End Class
I've also added a Ribbon item (via Add New Item... menu option) in designer mode (not xml) - and then add a button. Then I go to code and try to call the function and I get this error when using:
MsgBox(Globals.ThisAddIn.getRowCount())
Which I got from this link: Calling a procedure within another class
To be honest, I've been trying a myriad things and I've been getting so many errors. I've been looking online as well for a tutorial on creating my own Excel Addin from scratch with no real luck. I would like not to use Add-In-Express since that's a third party app and I have to create an Excel add-in for my company from scratch.
Does anyone have an idea on how I can create a vb.net coded Excel Addin (2007) that I can use as a template or guide? I've tried several and many rely on Add-In-express and I really cannot go that way. I have a lot of VBA code (natural VBA so it's in a module in an my excel files' VBA/Developer section) and I think I can translate those from VBA/VB6 to VB.Net format so that's not my concern. It is really about getting to code my own Excel Addin in VB.Net. Any help would really be great. Thank you.
*note: I would also like not to have to ask coworkers (or do myself) to just add to the quick access toolbar the functions and subs I've created since that's really not a solution, considering that those buttons will be there when they create or open another workbook. Essentially, I've got to create my own excel addin in vb.net. Thank you once again.
The issue has to do with the definitions in Microsoft.Office.Tools.Excel and Microsoft.Office.Interop.Excel. To code an "Interop" version you could use this:
Public Function getRowCount() As Long
Dim thisWB As Excel.Workbook = Application.ActiveWorkbook
Dim activWS As Excel.Worksheet = CType(thisWB.ActiveSheet, Excel.Worksheet)
Return activWS.UsedRange.Rows.Count
End Function
To extend the functionality of the Native objects and use VSTO, you could do it like this:
Public Function getRowCount() As Long
Dim NativeWorkbook As Excel.Workbook = Application.ActiveWorkbook
Dim NativeWorksheet As Excel.Worksheet = CType(NativeWorkbook.ActiveSheet, Excel.Worksheet)
Dim thisWB As Workbook = Nothing
Dim activWS As Worksheet = Nothing
If NativeWorkbook IsNot Nothing Then
thisWB = Globals.Factory.GetVstoObject(NativeWorkbook)
End If
If NativeWorksheet IsNot Nothing Then
activWS = Globals.Factory.GetVstoObject(NativeWorksheet)
End If
Return activWS.UsedRange.Rows.Count
End Function
This is a function you can put in ThisAddin.vb that will create a new Worksheet. Note that this function names the Worksheet and adds it to the end.
Public Function AddWorkSheet(sheetName As String) As Worksheet
Dim wk = Application.ActiveWorkbook
Dim ws As Worksheet = Nothing
Try
ws = CType(wk.Sheets.Add(, wk.Sheets(wk.Sheets.Count)), Worksheet)
ws.Name = sheetName
Catch ex As Exception
Throw
Finally
AddWorkSheet = ws
End Try
End Function
To use this outside of ThisAddin.vb you could do something like this:
Dim ws As Excel.Worksheet
Dim newSheetName As String
.
'
ws = Globals.ThisAddIn.AddWorkSheet(newSheetName)

vb.net & office: Unable to cast COM object of type 'Microsoft.Office.Interop.Excel.ApplicationClass'

I'm developing a vb.net application and it should open and handle a excel file.
The problem is that in my pc (and the same could happen in other pc where it could be installed) I have Visio version 2013 and Office (excel, word, etc..) version 2010. Integrating excel in vb is so simple because more or less automatic, done in few steps.. but in the same time so stupid: calling interop.Excel functions, it addresses to the newest version of office intalled (2013), but I don't have excel for that version!
I searched a lot on the web about this issue, and every where I found the solution of deleting a registry key, well, it works fine, but every time I use Visio, it seems the registry key is recreated again.
My questions are:
can I select which version of excel I would like to link my application?
I can understand that fixing the version I should handle any office versions
manually.. but maybe I prefer doing this..
can I copy a dll in the application folder to be sure that the app uses that
version? I tried with Microsoft.Office.Interop.Excel.dll and Office.dll but still the issue
I don't want to follow the way of deleting the registry key programmatically, is not safe in my opinion..
I can't believe that the integration between office and .net is so stupid that is not able to use the right version of excel installed!!
;-P
Code:
Dim fileTest As String = FilePath
Dim APP As New Application
MsgBox(APP.Version)
Dim oSheet As Excel.Worksheet = Nothing
Dim workbook As Excel.Workbook = Nothing
Dim IndexFound As Integer = 0
Dim StartRow As Integer = 10
Dim DateSelected As String = ""
Dim resultOK As Boolean = False
Try
workbook = APP.Workbooks.Open(fileTest)
oSheet = workbook.Worksheets("Activities")
APP.DisplayAlerts = False
oSheet.Range("A2").Value = "test"
oSheet.Range("B3").Value = "Ciao"
Catch ex As Exception
MsgBox("Error: " + ex.Message)
If Not resultOK Then
If Not workbook Is Nothing Then
workbook.Close()
While System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook) > 0
End While
workbook = Nothing
End If
oSheet = Nothing
workbook = Nothing
APP.Quit()
System.Runtime.InteropServices.Marshal.ReleaseComObject(APP)
APP = Nothing
GC.Collect()
GC.WaitForPendingFinalizers()
End If
End Try
End Sub
Thanks
Andrea

Application not released from Task Manager [duplicate]

This question already has answers here:
Application not quitting after calling quit
(11 answers)
Closed 7 years ago.
I'm trying to write some data from my windowsform into a Excel file, this works.
' Excel load data
Dim oExcelApp As New Microsoft.Office.Interop.Excel.Application
Dim oWorkBook As Microsoft.Office.Interop.Excel.Workbook
Dim oWorkSheet As Microsoft.Office.Interop.Excel.Worksheet
oWorkBook = oExcelApp.Workbooks.Open("C:\Temp\Test.xlsx")
oWorkSheet = oWorkBook.Worksheets(1)
oWorkSheet.Range("A1").Value = "Test"
oWorkBook.Save()
oWorkBook.Close()
Problem is: When I am done Excel is still running in my task manager. When I press the button like 10 times there are 10 Excel references in my task manager.
Question: How can I fully unload Excel after writing the value into the Excel?
You need to Quit Microsoft Excel and then release the objects.
Code referenced from this answer: The proper way to dispose Excel com object using VB.NET? and Excel application not quitting after calling quit
'Excel load data
Dim oExcelApp As New Microsoft.Office.Interop.Excel.Application
Dim oWorkBook As Microsoft.Office.Interop.Excel.Workbook
Dim oWorkSheet As Microsoft.Office.Interop.Excel.Worksheet
oWorkBook = oExcelApp.Workbooks.Open("C:\Temp\Test.xlsx")
oWorkSheet = oWorkBook.Worksheets(1)
oWorkSheet.Range("A1").Value = "Test"
oWorkBook.Save()
oWorkBook.Close()
oExcelApp.Quit()
'Release object references.
releaseObject(oWorkSheet)
releaseObject(oWorkBook)
releaseObject(oExcelApp)
----------------------------------------------------------------------------
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
You have to close the connection you just opened. You can do this by adding this line after your current code:
oExcelApp.Quit();
Source & more information: here
More information about the quit() method here.
Important: if you have open workbooks that are not saved yet, this method will show a dialog box asking to save.
If you don't want this, you either have to (1): save all open workbooks or (2) setting DisplayAlerts to false.
(1)
workbooks.Save()
(2)
oExcelApp.DisplayAlerts = false

Reading excel files in vb.net leaves excel process hanging

The following code works fine but seems to leave instances of excel.exe running in the background. How do I go about closing out this sub properly?
Private Sub ReadExcel(ByVal childform As Fone_Builder_Delux.frmData, ByVal FileName As String)
' In progress
childform.sampleloaded = False
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
xlApp = New Excel.ApplicationClass
xlWorkBook = xlApp.Workbooks.Open(FileName)
xlWorkSheet = xlWorkBook.Worksheets(1)
Dim columnrange = xlWorkSheet.Columns
Dim therange = xlWorkSheet.UsedRange
childform.datagridHeaders.Columns.Add("", "") ' Super imporant to add a blank column, could improve this
For cCnt = 1 To therange.Columns.Count
Dim Obj = CType(therange.Cells(1, cCnt), Excel.Range)
childform.datagridSample.Columns.Add(Obj.Value, Obj.Value)
childform.datagridHeaders.Columns.Add(Obj.Value, Obj.Value)
Next
For rCnt = 2 To therange.Rows.Count
Dim rowArray(therange.Columns.Count) As String
For cCnt = 1 To therange.Columns.Count
Dim Obj = CType(therange.Cells(rCnt, cCnt), Excel.Range)
Dim celltext As String
celltext = Obj.Value.ToString
rowArray((cCnt - 1)) = celltext
'MsgBox(Obj.Value)
Next
childform.datagridSample.Rows.Add(rowArray)
Next
AdjustHeaders(childform)
childform.sampleloaded = True
End Sub
Short answer: close each item appropriately, then call FinalReleaseComObject on them.
GC.Collect()
GC.WaitForPendingFinalizers()
If xlWorkSheet Is Nothing Then Marshal.FinalReleaseComObject(xlWorkSheet)
If xlWorkBook Is Nothing Then
xlWorkBook.Close(false, false)
Marshal.FinalReleaseComObject(xlWorkBook)
End If
xlApp.Quit()
Marshal.FinalReleaseComObject(xlApp)
Long answer: read this answer to another question (the entire post is helpful too).
I ran into this problem and what I found worked was making sure I called the Close() method on all Workbook and Workbooks objects, as well as the Quit() method on the Excel Application object. I also call System.Runtime.InteropServices.Marshal.ReleaseComObject on every Excel object was instantiated. I do all this in reverse order of age, so the newest object gets cleaned up first and the oldest, which is the Application object, gets taken care of last. I don't know if the order really matters, but it seems like it might.
I've seen examples where GC.Collect() was called at the very end, but I've never had to do that to get the excel.exe process to end.