Results 1 to 18 of 18

Thread: [RESOLVED] Excel won't quit

  1. #1

    Thread Starter
    Member
    Join Date
    Mar 2010
    Posts
    58

    Resolved [RESOLVED] Excel won't quit

    So I have a little gui that will read a given spreadsheet and list all the "valid" sheets. This happens when a user presses a button.

    here is my code:

    VB.NET Code:
    1. Private Sub bttnScanWorksheets_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bttnScanWorksheets.Click
    2.         If System.IO.File.Exists(TextBox1.Text) = True Then
    3.  
    4.             'Clear checkbox area
    5.             CheckedListBox1.Items.Clear()
    6.  
    7.             ' Open excel
    8.             Dim excelapp As Excel.Application
    9.             Dim WB As Excel.Workbook
    10.             Dim WS As Excel.Worksheet
    11.             excelapp = New Excel.Application
    12.             WB = excelapp.Workbooks.Open(TextBox1.Text)
    13.             Dim CheckValid As Boolean
    14.             Dim SheetsAdded As Boolean = False
    15.  
    16.             ' Cycle through each sheet
    17.             For Each WS In WB.Worksheets
    18.                 Try
    19.                     CheckValid = True
    20.                     If WS.Range("B4").Value.ToString <> "Employee Name:" Then
    21.                         CheckValid = False
    22.                     End If
    23.                     If WS.Range("H4").Value.ToString <> "Week No.:" Then
    24.                         CheckValid = False
    25.                     End If
    26.                     If WS.Range("F8").Value.ToString <> "Cost" Then
    27.                         CheckValid = False
    28.                     End If
    29.  
    30.                     ' Add the sheet to the list
    31.                     If CheckValid = True Then
    32.                         CheckedListBox1.Items.Add(WS.Name) ' Populate the checkbox area
    33.                         SheetsAdded = True
    34.                     End If
    35.                 Catch ex As NullReferenceException ' Catch errors that arrise from merged cells.
    36.                 Catch ex As Exception
    37.                     MsgBox(ex.ToString) ' any other errors will be caught here
    38.                 End Try
    39.             Next
    40.  
    41.             If SheetsAdded = False Then
    42.                 MsgBox("There were no valid sheets in this workbook.")
    43.             End If
    44.  
    45.             ' Close Excel
    46.             WB.Close()
    47.             excelapp.Quit()
    48.             Marshal.ReleaseComObject(excelapp)
    49.             excelapp = Nothing
    50.             GC.Collect()
    51.             GC.WaitForPendingFinalizers()
    52.             GC.Collect()
    53.         Else
    54.             MsgBox("That file does not exist")
    55.         End If
    56.     End Sub

    The problem is that Excel.exe doesn't quit until the program closes for some reason. This causes the spreadsheet to remain read only until the program is closed.

    Any ideas why excel isn't closing properly?

  2. #2
    Frenzied Member HanneSThEGreaT's Avatar
    Join Date
    Nov 2003
    Location
    Vereeniging, South Africa
    Posts
    1,492

    Re: Excel won't quit

    Try something like this - you almost had it :

    Code:
    xlbook.Close 'close worbook
    '...do the same as the following for range references if any, and all the excel stuff you've used...
    .Marshal.ReleaseComObject(ws) 'the worksheet
    .InteropServices.Marshal.ReleaseComObject(xlbook) 'the workbook
    
    xlapp.Quit() 'Then quit
    
    .Marshal.ReleaseComObject(xlapp) 'then release the application
    VB.NET MVP 2008 - Present

  3. #3

    Thread Starter
    Member
    Join Date
    Mar 2010
    Posts
    58

    Re: Excel won't quit

    Ok, I changed it to this:

    vb.net Code:
    1. ' Close Excel
    2.             WB.Close()            
    3.             Marshal.ReleaseComObject(WB)
    4.             excelapp.Quit()
    5.             'excelapp = Nothing
    6.             Marshal.ReleaseComObject(excelapp)
    7.             GC.Collect()
    8.             GC.WaitForPendingFinalizers()
    9.             GC.Collect()

    same problem. Excel closes, but only when I exit the program.

    edit: I have the same closing method in another function, which works how I would expect it too.
    Last edited by dethredic; Mar 31st, 2010 at 12:16 PM.

  4. #4
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,974

    Re: Excel won't quit

    You have missed out WS.

  5. #5

    Thread Starter
    Member
    Join Date
    Mar 2010
    Posts
    58

    Re: Excel won't quit

    Quote Originally Posted by si_the_geek View Post
    You have missed out WS.
    If I add:

    WS.Close() above WB.Close() then I get a "MissingMemberException was unhanded"

  6. #6
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,974

    Re: Excel won't quit

    That is to be expected, because the worksheet object does not have a method with that name (or any method which serves that purpose).

    Try what HanneSThEGreaT suggested:
    Code:
    .Marshal.ReleaseComObject(ws) 'the worksheet

  7. #7

    Thread Starter
    Member
    Join Date
    Mar 2010
    Posts
    58

    Re: Excel won't quit

    That does not help either.

    I am starting to think I am closing it right, but there is something else that is causing it to stay open because it closes fine in another function.

  8. #8

    Thread Starter
    Member
    Join Date
    Mar 2010
    Posts
    58

    Re: Excel won't quit

    any other ideas?

  9. #9
    PowerPoster cicatrix's Avatar
    Join Date
    Dec 2009
    Location
    Moscow, Russia
    Posts
    3,654

    Re: Excel won't quit

    Have you monitored with Task Manager whether excel.exe process actually closes after excelapp.Quit() and how many excel.exe instances do you have? Does your workbook contain some other embedded com objects or OLE links? Try it with an empty workbook.

  10. #10
    Frenzied Member
    Join Date
    Jul 2009
    Posts
    1,103

    Re: Excel won't quit

    you may try this:
    Code:
       Public Sub releaseobject(ByVal obj As Object)
            Try
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
                obj = Nothing
            Catch ex As Exception
                obj = Nothing
            End Try
            GC.Collect()
        End Sub
        
        'after closing the workbook add this
        apl.Quit()
    
            releaseobject(apl)
            releaseobject(wrkbk)
            releaseobject(wrksht)

    If you find my reply helpful , then rate it

  11. #11

    Thread Starter
    Member
    Join Date
    Mar 2010
    Posts
    58

    Re: Excel won't quit

    Quote Originally Posted by cicatrix View Post
    Have you monitored with Task Manager whether excel.exe process actually closes after excelapp.Quit() and how many excel.exe instances do you have? Does your workbook contain some other embedded com objects or OLE links? Try it with an empty workbook.
    I did monitor the task manager. As soon as I hit my button an excel.exe appears. I then hit another button which opens up the same spread sheet and does similar stuff. Another excel.exe pops up, but then goes away (it closes like I have shown in my original post). I then hit the first button again and no new excel.exe is added (I am not sure if it closes and opens again really fast or not)

    I then tried choosing a different workbook, and "invalid one". I got the msgbox: MsgBox("There were no valid sheets in this workbook."). Another excel.exe got opened. I clicked "OK" and they both closed (hurray?).

    Finally I started a new workbook and filled in the 3 required cells. I then tried that and no excel.exe got opened!

    I am now super confused how it closes in another function and if it isn't valid, but doesn't if this function.


    @ gautamshaw: thanks but that didn't help

  12. #12
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,974

    Re: Excel won't quit

    I don't do much work in VB.Net, but based on lots of previous work with Excel from VB6 I recommend using gautamshaw's releaseobject in this order:
    Code:
                releaseobject(WS)
                WB.Close()
                releaseobject(WB)
                excelapp.Quit()
                releaseobject(excelapp)
    If that doesn't fix it, try moving the first line to just before the end of the For loop.

  13. #13

    Thread Starter
    Member
    Join Date
    Mar 2010
    Posts
    58

    Re: Excel won't quit

    Quote Originally Posted by si_the_geek View Post
    I don't do much work in VB.Net, but based on lots of previous work with Excel from VB6 I recommend using gautamshaw's releaseobject in this order:
    Code:
                releaseobject(WS)
                WB.Close()
                releaseobject(WB)
                excelapp.Quit()
                releaseobject(excelapp)
    If that doesn't fix it, try moving the first line to just before the end of the For loop.
    Again this didn't work. I don't think it is a problem with how I am closing it (because it works other places), but something else must be the problem, or maybe the workbook itself because the close worked on other workbooks.

  14. #14

    Thread Starter
    Member
    Join Date
    Mar 2010
    Posts
    58

    Re: Excel won't quit

    Ok, I have done some rigorous testing and have some new info.

    If the database is empty then excel quits as expected.
    If the database is not empty then excel does not quit until the program exits.

    code:
    using the release object function from above.
    vb Code:
    1. Function PopulateCheckBoxArea()
    2.         If System.IO.File.Exists(TextBox1.Text) = True Then
    3.  
    4.             'Clear checkbox area
    5.             CheckedListBox1.Items.Clear()
    6.  
    7.             ' Open excel
    8.             Dim excelapp As Excel.Application
    9.             Dim WB As Excel.Workbook
    10.             Dim WS As Excel.Worksheet
    11.             excelapp = New Excel.Application
    12.             WB = excelapp.Workbooks.Open(TextBox1.Text)
    13.             Dim CheckValid As Boolean
    14.             Dim SheetsAdded As Boolean = False
    15.  
    16.             ' Cycle through each sheet
    17.             For Each WS In WB.Worksheets
    18.                 Try
    19.                     CheckValid = True
    20.                     If WS.Range("B4").Value.ToString <> "Employee Name:" Then
    21.                         CheckValid = False
    22.                     End If
    23.                     If WS.Range("H4").Value.ToString <> "Week No.:" Then
    24.                         CheckValid = False
    25.                     End If
    26.                     If WS.Range("F8").Value.ToString <> "Cost" Then
    27.                         CheckValid = False
    28.                     End If
    29.  
    30.                     ' Check to see if the sheet has already been added to the database
    31.                     If CheckValid = True Then
    32.  
    33.                         ' Get name of employee from spreadsheet
    34.                         Dim aName As Array
    35.                         aName = Split(WS.Range("C4").Value, " ")
    36.                         Dim nameexists = False
    37.                         Dim sheetadded = False
    38.  
    39.                         ' Check if the Employee is already in the Database
    40.                         Dim currentemployeeID As Int32
    41.                         Dim aEmployeeID As Int32
    42.  
    43.                         Using connection As New SqlConnection(ConnectionString)
    44.                             Using command As New SqlCommand("SELECT NameFirst, NameLast, EmployeeID FROM Employees", _
    45.                                                           connection)
    46.                                 connection.Open()
    47.                                 Using reader As SqlDataReader = command.ExecuteReader()
    48.                                     While reader.Read()
    49.                                         currentemployeeID = reader("EmployeeID")
    50.                                         If aName(0) = RemoveWhiteSpace(reader("NameFirst")) Then
    51.                                             If aName(1) = RemoveWhiteSpace(reader("NameLast")) Then
    52.                                                 ' The name exists in the database, get the EmployeeID to match the name
    53.                                                 aEmployeeID = currentemployeeID
    54.                                                 nameexists = True
    55.                                             End If
    56.                                         End If
    57.                                     End While
    58.                                 End Using
    59.                             End Using
    60.                         End Using
    61.  
    62.  
    63.                         ''''' Timesheet Table ''''''
    64.                         If nameexists = True Then
    65.  
    66.                             Dim aWeekNumber As Int32 = WS.Range("I4").Value
    67.  
    68.                             Using connection As New SqlConnection(ConnectionString)
    69.                                 Using command As New SqlCommand("SELECT TimesheetID, EmployeeID, WeekNumber FROM Timesheet", _
    70.                                                               connection)
    71.                                     connection.Open()
    72.                                     Using reader As SqlDataReader = command.ExecuteReader()
    73.                                         While reader.Read()
    74.                                             If aWeekNumber = RemoveWhiteSpace(reader("WeekNumber")) Then
    75.                                                 If aEmployeeID = RemoveWhiteSpace(reader("EmployeeID")) Then
    76.                                                     ' The Timesheet has already been added
    77.                                                     sheetadded = True
    78.                                                 End If
    79.                                             End If
    80.                                         End While
    81.                                     End Using
    82.                                 End Using
    83.                             End Using
    84.                         End If
    85.  
    86.                         ' Add the sheet to the list
    87.                         If sheetadded = False Then
    88.                             CheckedListBox1.Items.Add(WS.Name) ' Populate the checkbox area
    89.                             SheetsAdded = True
    90.                         End If
    91.  
    92.                     End If
    93.                 Catch ex As NullReferenceException ' Catch errors that arrise from merged cells.
    94.                 Catch ex As Exception
    95.                     MsgBox(ex.ToString) ' any other errors will be caught here
    96.                 End Try
    97.                 Marshal.ReleaseComObject(WS)
    98.             Next
    99.  
    100.  
    101.             ' Close Excel
    102.             WB.Close()
    103.             Marshal.ReleaseComObject(WB)
    104.             excelapp.Quit()
    105.             Marshal.ReleaseComObject(excelapp)
    106.             excelapp = Nothing
    107.             GC.Collect()
    108.             GC.WaitForPendingFinalizers()
    109.             GC.Collect()
    110.  
    111.             If SheetsAdded = False Then
    112.                 MsgBox("There were no valid sheets in this workbook.")
    113.             End If
    114.  
    115.         Else
    116.             MsgBox("That file does not exist")
    117.         End If
    118.  
    119.     End Function

  15. #15
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,974

    Re: Excel won't quit

    There are only three things there that seem like they could be potential issues... the first is the RemoveWhiteSpace function (which I presume has nothing to do with Excel, and thus is irrelevant), and the other two are these two lines of code:
    Code:
                                Dim aWeekNumber As Int32 = WS.Range("I4").Value
                                CheckedListBox1.Items.Add(WS.Name) ' Populate the checkbox area
    Try altering each of those so they don't refer to Excel... hopefully you'll find that one of them is the culprit.

  16. #16

    Thread Starter
    Member
    Join Date
    Mar 2010
    Posts
    58

    Re: Excel won't quit

    Quote Originally Posted by si_the_geek View Post
    There are only three things there that seem like they could be potential issues... the first is the RemoveWhiteSpace function (which I presume has nothing to do with Excel, and thus is irrelevant), and the other two are these two lines of code:
    Code:
                                Dim aWeekNumber As Int32 = WS.Range("I4").Value
                                CheckedListBox1.Items.Add(WS.Name) ' Populate the checkbox area
    Try altering each of those so they don't refer to Excel... hopefully you'll find that one of them is the culprit.
    Dim aWeekNumber As Int32 = WS.Range("I4").Value was the problem.

    Thanks so much.

  17. #17
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,974

    Re: [RESOLVED] Excel won't quit

    Excellent... I'm glad we got there at last

    For the sake of anyone else who has a similar problem later, can you show the 'corrected' version of that line?

  18. #18

    Thread Starter
    Member
    Join Date
    Mar 2010
    Posts
    58

    Re: [RESOLVED] Excel won't quit

    I took it out and just use the value directly (without declaring it)
    vb Code:
    1. ''''' Timesheet Table ''''''
    2.                         If nameexists = True Then
    3.  
    4.                             Using connection As New SqlConnection(ConnectionString)
    5.                                 Using command As New SqlCommand("SELECT TimesheetID, EmployeeID, WeekNumber FROM Timesheet", _
    6.                                                               connection)
    7.                                     connection.Open()
    8.                                     Using reader As SqlDataReader = command.ExecuteReader()
    9.                                         While reader.Read()
    10.                                            'change was made below
    11.                                             ' If aWeekNumber = RemoveWhiteSpace(reader("WeekNumber")) Then
    12.                                             If WS.Range("I4").Value = RemoveWhiteSpace(reader("WeekNumber")) Then
    13.                                                 If aEmployeeID = RemoveWhiteSpace(reader("EmployeeID")) Then
    14.                                                     ' The Timesheet has already been added
    15.                                                     sheetadded = True
    16.                                                 End If
    17.                                             End If
    18.                                         End While
    19.                                     End Using
    20.                                 End Using
    21.                             End Using
    22.                         End If

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