Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to close Excel process from VB.NET app

I created the class below to open and gather the names of worksheets in an excel file. It does as it should in opening the file and returning the names of the each individual worksheet. Unfortunatly, I'm unable to close the file. This keeps the Excel.exe process hanging. Even after I attempt to close it at the bottom of this class the process still hangs. I have to manually goto Windows Task Manager and kill the process before I can use the file again. Even if I exit out of the application it still is out there. Any suggestion on how to kill this process from the code?

Imports Excel = Microsoft.Office.Interop.Excel

Public Class ExcelWrapper

Dim strTypeSelection As String = String.Empty
Dim strFilePath As String = String.Empty

Function GetWorksheetsByName(ByVal strfilePath As String) As Array

    Dim xlsApp As Excel.Application
    Dim xlsWorkBook As Excel.Workbook

    xlsApp = New Excel.Application
    xlsWorkBook = xlsApp.Workbooks.Open(strfilePath)
    Dim intWsCount As Integer = xlsApp.Worksheets.Count

    Dim sarWorksheetName(intWsCount - 1) As String

    Dim i As Integer = 0
    'gathers the names off all the worksheets 
    For Each totalWorkSheets In xlsApp.Worksheets
        sarWorksheetName(i) = totalWorkSheets.Name
        i += 1
    Next totalWorkSheets

    xlsWorkBook.Close(strfilePath)
    xlsApp.DisplayAlerts = False
    xlsApp.Quit()

    Return sarWorksheetName
End Function

End Class
like image 327
rross Avatar asked Jan 20 '23 22:01

rross


2 Answers

I've run into this issue before as well, and as I recall the solution was to call Marshal.ReleaseComObject(Object obj) or Marshal.FinalReleaseComObject(Object obj) on all of the objects that the come from the Office libraries. I could very easily be wrong though. Good luck, Office automation is a huge pain.

like image 58
MarkPflug Avatar answered Jan 22 '23 13:01

MarkPflug


For each reference try adding;

System.Runtime.InteropServices.Marshal.ReleaseComObject(xxx)
xxx = nothing

(http://support.microsoft.com/kb/317109)

like image 32
Alex K. Avatar answered Jan 22 '23 12:01

Alex K.