终止在任务管理器vb.net中最后创建的Excel实例

时间:2017-11-09 18:19:04

标签: excel vb.net

你能帮我解决问题吗?

我打开了几个Excel实例(任务管理器中的EXCEL.EXE),我想杀死上次打开的实例。现在我可以杀死第一个实例,但我想杀死最后一个:

Sub Main()
    Dim dictExe As Object
    dictExe = CreateObject("Scripting.Dictionary")

    Dim oServ As Object
    Dim cProc
    Dim oProc As Object
    oServ = GetObject("winmgmts:")
    cProc = oServ.ExecQuery("Select * from Win32_Process")
    For Each oProc In cProc
        If oProc.Name = "EXCEL.EXE" Then
            dictExe.Add(oProc, oProc.CreationDate)
        End If
    Next

    For Each oProcCatia In dictExe
        If oProcCatia.Name = "EXCEL.EXE" Then
            Dim errReturnCode
            errReturnCode = oProcCatia.Terminate()
            Exit Sub
        End If
    Next
End Sub

我想要杀死字典中的实例具有最大的创建日期,但我不知道如何。 那么问题也可以是,如何从字典中获取最大值的密钥?

1 个答案:

答案 0 :(得分:1)

我会放弃使用Scripting.Dictionary并只保留最新CreationDate的引用:

Sub Main()
    Dim oServ As Object
    Dim cProc
    Dim oProc As Object
    Dim oToBeRemovedProc As Object
    Dim oToBeRemovedCreationDate As Object

    oServ = GetObject("winmgmts:")
    cProc = oServ.ExecQuery("Select * from Win32_Process")
    For Each oProc In cProc
        If oProc.Name = "EXCEL.EXE" Then
            '::: No good checking values against Nothing
            If oToBeRemovedProc Is Nothing Then
                oToBeRemovedProc = oProc
                oToBeRemovedCreationDate = oProc.CreationDate
            End If

            '::: Is the current hold value older than this one?
            If oToBeRemovedCreationDate < oProc.CreationDate Then
                oToBeRemovedProc = oProc
                oToBeRemovedCreationDate = oProc.CreationDate
            End If
        End If
    Next

    '::: Do we actually have something to remove?
    If Not oToBeRemovedProc Is Nothing Then
        oToBeRemovedProc.Terminate()
        oToBeRemovedProc = Nothing
        oToBeRemovedCreationDate = Nothing 
    End If
End Sub