Excel process still runs after closing in VB.net

前端 未结 4 594
孤城傲影
孤城傲影 2020-12-19 16:43

My question is basically just how to end the Excel.exe process that runs when using excel. In the application I open and use an excel workbook with a couple sheets, then lea

4条回答
  •  忘掉有多难
    2020-12-19 17:20

    Good solution Alex, we shouldn't have to do this, but we do, EXCEL just won't end. I took your solution and created the code below, I call ExcelProcessInit before my app imports or exports with Excel, then call ExcelProcessKill after it's complete.

    Private mExcelProcesses() As Process
    
    Private Sub ExcelProcessInit()
      Try
        'Get all currently running process Ids for Excel applications
        mExcelProcesses = Process.GetProcessesByName("Excel")
      Catch ex As Exception
      End Try
    End Sub
    
    Private Sub ExcelProcessKill()
      Dim oProcesses() As Process
      Dim bFound As Boolean
    
      Try
        'Get all currently running process Ids for Excel applications
        oProcesses = Process.GetProcessesByName("Excel")
    
        If oProcesses.Length > 0 Then
          For i As Integer = 0 To oProcesses.Length - 1
            bFound = False
    
            For j As Integer = 0 To mExcelProcesses.Length - 1
              If oProcesses(i).Id = mExcelProcesses(j).Id Then
                bFound = True
                Exit For
              End If
            Next
    
            If Not bFound Then
              oProcesses(i).Kill()
            End If
          Next
        End If
      Catch ex As Exception
      End Try
    End Sub
    
    Private Sub MyFunction()
      ExcelProcessInit()
      ExportExcelData() 'Whatever code you write for this...
      ExcelProcesKill()
    End Sub
    

提交回复
热议问题