Results 1 to 10 of 10

Thread: [RESOLVED] Closing Excel

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Jan 2012
    Location
    Florida
    Posts
    285

    Resolved [RESOLVED] Closing Excel

    Okay so my program opens excel, reads a few cells, and closes excel. But, it does not fully close excel and after multiple runs, I have multiple EXCEL.EXE *32 in my process list. It also asks for a save when it's closing when there are no changes being made, is there any way to avoid this? And how do you get Excel to fully close?

    Imports Excel = Microsoft.Office.Interop.Excel
    vb Code:
    1. Public Sub XLMain()
    2.         xlApp = CType(CreateObject("Excel.Application"), Excel.Application)
    3.         xlBook = xlApp.Workbooks.Open(strExcelPath)
    4.         xlSheet = CType(xlBook.Worksheets(1), Excel.Worksheet)
    5.         'Stuffs to be did
    6.         ReadXL()
    7.         ImportXL()
    8.         'Close Excel:
    9.         CloseExcel()
    10.     End Sub
    11.     Public Sub CloseExcel()
    12.         xlBook.Close()
    13.         xlApp.Quit()
    14.     End Sub
    15.     Public Sub ReadXL()
    16.         Try
    17.             ordernumber = xlSheet.Cells(5, "C").Value.ToString
    18.             owner1 = xlSheet.Cells(6, "C").Value.ToString
    19.             county = xlSheet.Cells(6, "I").Value.ToString
    20.             fulladdress = xlSheet.Cells(7, "C").Value.ToString
    21.             address = Mid(fulladdress, 1, InStr(fulladdress, ",") - 1)
    22.             halfaddress = Mid(fulladdress, address.Length + 2)
    23.             zip = Mid(fulladdress, fulladdress.Length - 4, 5)
    24.             city = Mid(halfaddress, 1, InStr(halfaddress, ",") - 1)
    25.             state = Mid(fulladdress, address.Length + city.Length + 4, 2)
    26.         Catch ex As Exception
    27.             MsgBox(ex.ToString)
    28.         End Try
    29.     End Sub

    I also just tried this, and it did not work:
    vb Code:
    1. Public Sub CloseExcel()
    2.         'xlBook.Close()
    3.         'xlApp.Quit()
    4.         System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp)
    5.         GC.Collect()
    6.     End Sub

    Just tried this also, and it did not work:
    vb Code:
    1. Dim strExcelPath As String = "C:\Users\Aj\Desktop\Tax_Research_Template_2010_-_Excel.xls"
    2.     Dim xlApp = New Excel.Application()
    3.     Dim xlWbs = xlApp.Workbooks
    4.     Dim xlBook = xlWbs.Open(strExcelPath)
    5.     Dim xlSheet = xlBook.Worksheets(1)
    6.     Public Sub CloseExcel()
    7.         xlBook.Close()
    8.         xlApp.Quit()
    9.         xlBook = Nothing
    10.         xlWbs = Nothing
    11.         xlApp = Nothing
    12.     End Sub
    The program closes, without asking for a save, gets me the data I need, but remains in the process list.
    Using this for my Imports
    Code:
    Imports Excel = Microsoft.Office.Interop.Excel
    Last edited by thebuffalo; May 23rd, 2012 at 12:29 PM.

  2. #2
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,713

    Re: Closing Excel

    Hello,

    Right from the start what is wrong, how the automation is done from creating an instance of an Excel app to how you are assigning the variables for workbook and worksheet. Any time you can count more than one "." in a line of code working with Excel automation you are causing an object not to release (under normal conditions) when the code finishes executing commonly known as tunnelling.

    Code:
    xlApp = CType(CreateObject("Excel.Application"), Excel.Application)
    xlBook = xlApp.Workbooks.Open(strExcelPath)
    xlSheet = CType(xlBook.Worksheets(1), Excel.Worksheet)

    The following example used as provided you should open Task Manager to the Process tab and notice that Excel appears while in use then disappears because the method used to close and dispose are done in a proper sequence and no tunnelling is done. Excel automation when done half way correct looks easy while done correctly requires a great deal of work to ensure every object is disposed of properly.

    Requires an OpenDialog on the form this code is used. The default location is My Documents to find Excel files. Ignore the initial value for InitialPath variable.

    Code:
    Private Sub Button1_Click(
        ByVal sender As System.Object,
        ByVal e As System.EventArgs) Handles Button1.Click
    
        Dim InitialPath As String = "C:\DotnetLand2010\Excel\ExcelSoda\bin\Debug"
    
        OpenFileDialog1.Title = "Please select a file to open"
        OpenFileDialog1.FileName = ""
    
        If IO.Directory.Exists(InitialPath) Then
            OpenFileDialog1.InitialDirectory = InitialPath
        Else
            OpenFileDialog1.InitialDirectory =
                System.Environment.GetFolderPath(
                    Environment.SpecialFolder.MyDocuments)
        End If
    
        OpenFileDialog1.Filter = "Excel 2007 (*.xlsx)|*.xlsx|Excel pre 2007|*.xls"
    
        If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
            Dim xlApp As Excel.Application = Nothing
            Dim xlWorkBooks As Excel.Workbooks = Nothing
            Dim xlWorkBook As Excel.Workbook = Nothing
            Dim xlWorkSheet As Excel.Worksheet = Nothing
            xlApp = New Excel.Application
            xlApp.DisplayAlerts = False
            xlWorkBooks = xlApp.Workbooks
            xlWorkBook = xlWorkBooks.Open(OpenFileDialog1.FileName)
    
            xlApp.Visible = False
    
            xlWorkSheet = CType(xlWorkBook.ActiveSheet, Excel.Worksheet)
    
            Dim SingleCellToRead = xlWorkSheet.Range("A1")
            Dim A1_Value As String = String.Format("A1 = '{0}'", SingleCellToRead.Value)
    
            xlWorkBook.Close()
            xlApp.UserControl = True
            xlApp.Quit()
    
            If Not SingleCellToRead Is Nothing Then
                Marshal.FinalReleaseComObject(SingleCellToRead)
                SingleCellToRead = Nothing
            End If
            If Not xlWorkSheet Is Nothing Then
                Marshal.FinalReleaseComObject(xlWorkSheet)
                xlWorkSheet = Nothing
            End If
            If Not xlWorkBook Is Nothing Then
                Marshal.FinalReleaseComObject(xlWorkBook)
                xlWorkBook = Nothing
            End If
            If Not xlWorkBooks Is Nothing Then
                Marshal.FinalReleaseComObject(xlWorkBooks)
                xlWorkBooks = Nothing
            End If
            If Not xlApp Is Nothing Then
                Marshal.FinalReleaseComObject(xlApp)
                xlApp = Nothing
            End If
    
            MessageBox.Show(A1_Value)
    
        End If
    End Sub

  3. #3

    Thread Starter
    Hyperactive Member
    Join Date
    Jan 2012
    Location
    Florida
    Posts
    285

    Re: Closing Excel

    Okay this is what I have now and it is working, I could not get the Marshal command to work still.

    vb Code:
    1. Dim strExcelPath As String = "C:\Users\Aj\Desktop\Tax_Research_Template_2010_-_Excel.xls"
    2.     Dim xlApp = New Excel.Application()
    3.     Dim xlWbs = xlApp.Workbooks
    4.     Dim xlBook = xlWbs.Open(strExcelPath)
    5.     Dim xlSheet = xlBook.Worksheets(1)
    6.     Public Sub XLMain()
    7.         ReadXL()
    8.         ImportXL()
    9.         'Close Excel:
    10.         CloseExcel()
    11.     End Sub
    12.     Public Sub CloseExcel()
    13.         xlBook.Close()
    14.         xlApp.Quit()
    15.         KillProcess()
    16.         xlBook = Nothing
    17.         xlWbs = Nothing
    18.         xlApp = Nothing
    19.     End Sub
    20.     Public Sub KillProcess()
    21.         Dim proc = Process.GetProcessesByName("EXCEL.EXE")
    22.         For i As Integer = 0 To proc.Count - 1
    23.             proc(i).CloseMainWindow()
    24.         Next i
    25.     End Sub

    Is this a good way to do this? It is working, but I'm not sure if this is the best way or if it will work every time. It does not close Excel until the Test Form is closed, this is going to be a Class Library, will it close when it is called in this case? The .DLL will be running on a windows service 24/7

    Basically, Excel is still in the process list until the Form is closed now rather than when the KillProcess is called, if this is a class library instead of a form, will it do the same thing?
    Last edited by thebuffalo; May 23rd, 2012 at 01:02 PM.

  4. #4
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,713

    Re: Closing Excel

    What do you mean by not getting Marshal.FinalReleaseComObject to work?

    Also the following will cause an issue with disposal
    Code:
    Dim xlSheet = xlBook.Worksheets(1)
    If you need to select a worksheet this way then add the following to the end of my example right before the MessageBox

    Code:
    GC.Collect()
    GC.WaitForPendingFinalizers()
    GC.Collect()
    GC.WaitForPendingFinalizers()
    There is never a need to use your KillProcess code unless your code crashes before completion because of a run time exception. Under normal conditions what I have provided works. Get back to me about the Marshal.FinalReleaseComObject not working.

  5. #5

    Thread Starter
    Hyperactive Member
    Join Date
    Jan 2012
    Location
    Florida
    Posts
    285

    Re: Closing Excel

    I had System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp) and Marshal.ReleaseComObject(xlApp) in my CloseExcel but neither of them removed it from the process list, I never had a problem actually "closing" it but rather removing it as a process, but that being true it was never closed in the first place, it was just never visible so I wouldn't know.

    Code:
    GC.Collect()
    GC.WaitForPendingFinalizers()
    GC.Collect()
    GC.WaitForPendingFinalizers()
    This fixed it, thanks.
    Last edited by thebuffalo; May 23rd, 2012 at 01:14 PM.

  6. #6

    Thread Starter
    Hyperactive Member
    Join Date
    Jan 2012
    Location
    Florida
    Posts
    285

    Re: Closing Excel

    vb Code:
    1. Dim strExcelPath As String = "C:\Users\Aj\Desktop\Tax_Research_Template_2010_-_Excel.xls"
    2.     Dim xlApp = New Excel.Application()
    3.     Dim xlWbs = xlApp.Workbooks
    4.     Dim xlBook = xlWbs.Open(strExcelPath)
    5.     Dim xlSheet = xlBook.Worksheets(1)    
    6.     Public Sub CloseExcel()
    7.         xlBook.Close()
    8.         xlApp.Quit()
    9.         xlApp = Nothing
    10.         xlWbs = Nothing
    11.         xlBook = Nothing
    12.         xlSheet = Nothing
    13.         GC.Collect()
    14.         GC.WaitForPendingFinalizers()
    15.         GC.Collect()
    16.         GC.WaitForPendingFinalizers()
    17.     End Sub

  7. #7
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,713

    Re: Closing Excel

    See attached VS2010 project which uses the code I provided and also shows all open processes beginning with 'e' like Excel so you need not keep task manager open. Try CheckBox1 checked and unchecked (see comments inside)
    Attached Files Attached Files

  8. #8
    Karen Payne MVP kareninstructor's Avatar
    Join Date
    Jun 2008
    Location
    Oregon
    Posts
    6,713

    Re: Closing Excel

    Quote Originally Posted by thebuffalo View Post
    I had System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp) and Marshal.ReleaseComObject(xlApp) in my CloseExcel but neither of them removed it from the process list, I never had a problem actually "closing" it but rather removing it as a process, but that being true it was never closed in the first place, it was just never visible so I wouldn't know.

    Code:
    GC.Collect()
    GC.WaitForPendingFinalizers()
    GC.Collect()
    GC.WaitForPendingFinalizers()
    This fixed it, thanks.
    Cool!!! Make sure to look at the attached project in my reply before this one.

  9. #9

    Thread Starter
    Hyperactive Member
    Join Date
    Jan 2012
    Location
    Florida
    Posts
    285

    Re: [RESOLVED] Closing Excel

    My excel refuses to close again after the changes I had to make in order to have my .DLL work properly with a parent form:
    vb Code:
    1. Dim strExcelPath As String
    2.     Dim xlBook As Excel.Workbook
    3.     Dim xlWbs As Excel.Workbooks
    4.     Dim accConn = New OleDbConnection
    5. #Region "properties"
    6.     Public Property ExcelPath() As String
    7.         Get
    8.             Return strExcelPath
    9.         End Get
    10.         Set(ByVal value As String)
    11.             strExcelPath = value
    12.             xlBook = xlWbs.Open(strExcelPath)
    13.         End Set
    14.     End Property
    15.     Public Property AccessConn() As OleDbConnection
    16.         Get
    17.             Return accConn
    18.         End Get
    19.         Set(ByVal value As OleDbConnection)
    20.             accConn = value
    21.         End Set
    22.     End Property
    23. #End Region
    24.     Public Sub XLMain()
    25.         ReadXL()
    26.         ImportXL()
    27.     End Sub
    28.     'Functions/Subs
    29.     Public Sub ReadXL()
    30.         Dim xlApp = New Excel.Application
    31.         xlWbs = xlApp.Workbooks
    32.         Dim xlSheet = xlBook.Worksheets(1)
    33.         Try
    34.             ordernumber = xlSheet.Cells(5, "C").Value.ToString
    35.             owner1 = xlSheet.Cells(6, "C").Value.ToString
    36.             county = xlSheet.Cells(6, "I").Value.ToString
    37.             fulladdress = xlSheet.Cells(7, "C").Value.ToString
    38.             address = Mid(fulladdress, 1, InStr(fulladdress, ",") - 1)
    39.             halfaddress = Mid(fulladdress, address.Length + 2)
    40.             zip = Mid(fulladdress, fulladdress.Length - 4, 5)
    41.             city = Mid(halfaddress, 1, InStr(halfaddress, ",") - 1)
    42.             state = Mid(fulladdress, address.Length + city.Length + 4, 2)
    43.         Catch ex As Exception
    44.             MsgBox(ex.ToString)
    45.         End Try
    46.         xlBook.Close()
    47.         xlApp.Quit()
    48.         xlApp = Nothing
    49.         xlWbs = Nothing
    50.         xlBook = Nothing
    51.         xlSheet = Nothing
    52.         GC.Collect()
    53.         GC.WaitForPendingFinalizers()
    54.         GC.Collect()
    55.         GC.WaitForPendingFinalizers()
    56.     End Sub
    57.     Public Sub ImportXL()
    58.         Dim cmdInsert As New OleDbCommand("INSERT INTO Orders (OrderNumber, Owner1Full, County, City, State, Address, ZipCode) VALUES ('" & ordernumber & "', '" & owner1 & "', '" & county & "', '" & city & "', '" & state & "', '" & address & "', '" & zip & "')", accConn)
    59.         accConn.Open()
    60.         Try
    61.             cmdInsert.ExecuteNonQuery()
    62.         Catch ex As OleDbException
    63.             MsgBox(ex.ToString)
    64.         End Try
    65.         accConn.Close()
    66.     End Sub
    67. End Class

    It is back to closing EXCEL.EXE when the parent Form closes. Which is unacceptable as this will be a service running 24/7
    Last edited by thebuffalo; May 23rd, 2012 at 03:35 PM.

  10. #10

    Thread Starter
    Hyperactive Member
    Join Date
    Jan 2012
    Location
    Florida
    Posts
    285

    Re: [RESOLVED] Closing Excel

    vb Code:
    1. Public Sub callstuff()
    2.         tempExcel.AccessConn = accConn
    3.         tempExcel.ExcelPath = "C:\Users\Aj\Desktop\Tax_Research_Template_2010_-_Excel.xls"
    4.         tempExcel.XLMain()
    5.         GC.Collect()
    6.         GC.WaitForPendingFinalizers()
    7.         GC.Collect()
    8.         GC.WaitForPendingFinalizers()
    9.     End Sub

    Fixed.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width