vb.net EXCEL进程问题

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim pid As String
        pid = ""
        If System.Diagnostics.Process.GetProcessesByName("excel").Length > 0 Then
            Dim Proc As Process() = Process.GetProcessesByName("excel")
            For P = 0 To Proc.Length - 1
                'Proc(P).Kill()
                pid = Proc(P).Id
                If TextBox1.Text = "" Then
                    TextBox1.Text = pid
                Else
                    TextBox1.Text = TextBox1.Text & "," & pid
                End If
            Next
        End If
    End Sub
    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim ExlApp = CreateObject("Excel.Application")
        Dim xlbook = ExlApp.Workbooks
    End Sub
    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        Dim pid2 As String
        pid2 = ""
        If System.Diagnostics.Process.GetProcessesByName("excel").Length > 0 Then
            Dim Proc As Process() = Process.GetProcessesByName("excel")
            For P = 0 To Proc.Length - 1
                pid2 = Proc(P).Id
                If TextBox1.Text.Contains(pid2) = False Then
                    Proc(P).Kill()
                End If
            Next
        End If
    End Sub
End Class

以上是测试的代码。

TextBox1.Text 用于存放已有的EXCEL 进程PID

通常情况,用VB.NET 调用EXCEL 进程,会在进程中产生很多的EXCEL.EXE进程,一不小心,进程越累越多。

个人解决把那,用 Proc(P).Kill() 全部杀掉,但是问题出来了,假设有程序本身之外 正在工作的EXCEL ,同样会被杀掉。一度成为 一块心病。

一种不是办法的办法,用VB.NET创建新的 EXCEL 进程前,先记录下所有的 EXCEL 进程 PID(就是任务管理器中能看到的PID), 当程序运行完成后,再清理EXCEL 进程,当新的EXCEL 进程PID 不包括在原有的PID范围内,即可杀掉。该办法,任然没有解决 程序运行时,用户 产生的EXCEL 进程,导致程序崩溃的问题。

原文地址:https://www.cnblogs.com/RedLn/p/14681325.html