如何声明全局variables以从任务pipe理器中杀死第二个EXCEL.EXE

以下代码在任务pipe理器中打开两个EXCEL.EXE。

当Form1closures时,我想从任务pipe理器中杀掉第二个打开的EXCEL.EXE。

Imports Microsoft.Office.Interop Public Class Form1 Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load 'Kill all EXCEL.EXE process from Task Manager For Each prog As Process In Process.GetProcessesByName("EXCEL") prog.Kill() Next Dim FirstxlApp As New Excel.Application 'Open first EXCEL.EXE in the Task Manager Dim datestart As Date = Date.Now Dim SecondxlApp As New Excel.Application 'Open second EXCEL.EXE in the Task Manager Dim dateEnd As Date = Date.Now SecondxlApp.Visible = True Dim wb1 As Excel.Workbook wb1 = SecondxlApp.Workbooks.Open("C:\Book1.xlsx") End Sub Private Sub Form1_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing Dim xlp() As Process = Process.GetProcessesByName("EXCEL") For Each Process As Process In xlp If Process.StartTime >= datestart And Process.StartTime <= dateEnd Then Process.Kill() Exit For End If Next End Sub End Class 

如何声明全局variables以解决以下错误?

在这里输入图像说明

您的variablesdateEnddateStartFormClosing方法隐藏,因为它们只在Form_Load方法中声明。

将您的代码更改为:

Public Class Form1 Dim dateEnd, dateStart As DateTime Private Sub Form_load

然后他们将可以访问所有forms的方法。