Releasing Excel after using Interop

Posted by figus on Stack Overflow See other posts from Stack Overflow or by figus
Published on 2010-05-04T22:29:18Z Indexed on 2010/05/04 22:58 UTC
Read the original article Hit count: 261

Filed under:
|
|
|
|

Hi everyone

I've read many post looking for my answer, but all are similar to this: http://stackoverflow.com/questions/1610743/reading-excel-files-in-vb-net-leaves-excel-process-hanging

My problem is that I don't quit the app...

The idea is this:

If a User has Excel Open, if he has the file I'm interested in open... get that Excel instance and do whatever I want to do...

But I don't to close his File after I'm done... I want him to keep working on it, the problem is that when he closes Excel... The process keeps running... and running... and running after the user closes Excel with the X button...

this is how I try to do it

This piece is used to know if he has Excel open, and in the For I check for the file name I'm interested in.

    Try
        oApp = GetObject(, "Excel.Application")
        libroAbierto = True
        For Each libro As Microsoft.Office.Interop.Excel.Workbook In oApp.Workbooks
            If libro.Name = EquipoASeccionIdSeccion.Text & ".xlsm" Then
                Exit Try
            End If
        Next
        libroAbierto = False
    Catch ex As Exception
        oApp = New Microsoft.Office.Interop.Excel.Application
    End Try

here would be my code... if he hasn't Excel open, I create a new instance, open the file and everything else.

My code ends with this:

If Not libroAbierto Then
        libroSeccion.Close(SaveChanges:=True)
        oApp.Quit()
    Else
        oApp.UserControl = True
        libroSeccion.Save()
    End If    
    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(libroOriginal)
    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(libroSeccion)
    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(origen)
    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(copiada)
    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(oApp)
    libroOriginal = Nothing
    libroSeccion = Nothing
    oApp = Nothing
    origen = Nothing
    copiada = Nothing
    nuevosGuardados = True

So you can see that, if I opened the file, I call oApp.Quit() and everything else and the Excel Process ends after a few seconds (maybe 5 aprox.)

BUT if I mean the user to keep the file open (not calling Quit()), Excel process keeps running after the user closes Excel with the X button.

Is there any way to do what I try to do?? Control a open instance of excel and releasing everything so when the user closes it with the X button, the Excel Process dies normally???

Thanks!!!

© Stack Overflow or respective owner

Related posts about excel

Related posts about release