Terminating all explorer instances via VBA - Excel

笑着哭i 提交于 2019-12-10 15:55:35

问题


Private Sub CommandButton1_Click()
Dim objWMI As Object, objProcess As Object, objProcesses As Object

Set objWMI = GetObject("winmgmts://.")
Set objProcesses = objWMI.ExecQuery("Select * FROM Win32_Process Where Name = 'iexplore.exe'")

For Each objProcess In objProcesses
    objProcess.Terminate
Next

Set objProcesses = Nothing
Set objWMI = Nothing

Unload WebForm

End Sub    

Trying to use this as a way to close out all instances of Explorer before running some functions that retrieve data from web based servers, but am running into an issue when it attempts to close out an open browser with multiple tabs. If the user has only one IE window (one tab) open, then it closes it just fine and moves on; if these user has multiple windows open separately (not tabbed in one window), then it closes them all just fine and moves on; but for some reason, if one window is open with multiple tabs, then I get run-time error '-2147217406 (80041002)': "Not found". Any help working through this would be greatly appreciated.


回答1:


Not exactly what you asked, but another approach that uses powershell and includes an option (from here to close windows only where IE has been open for more than X seconds.

Sub Comesfast()
X2 = Shell("powershell.exe get-process iexplore | ? { ([DateTime]::Now - $_.StartTime).TotalSeconds -gt 05 } | stop-process", 1)
End Sub



回答2:


This problem is caused by way how IE is handling tabs. There is 1 main instance of IE and for each tab new process iexplore is created. Therefore when main host instance is closed also all tabs-related processes are closed. It causes error in your code, because collection you are enumerating is a snapshot of state from earlier state and you are trying to close not existing anymore processes. This could be observed in TaskManager.

Now answer how to improve your code (of course simple on error resume next would also help, but exiting after first closed instance could be not enough if user has more sessions opened):

Private Sub CommandButton1_Click()
Dim objWMI As Object, objProcess As Object, objProcesses As Object

    Do
        Set objWMI = GetObject("winmgmts://.")
        Set objProcesses = objWMI.ExecQuery("Select * FROM Win32_Process Where Name = 'iexplore.exe'")

        If objProcesses.Count > 0 Then
            For Each objProcess In objProcesses
                objProcess.Terminate
                Exit For
            Next
        End If
    Loop While objProcesses.Count > 0

    Set objProcesses = Nothing
    Set objWMI = Nothing

    Unload WebForm

End Sub


来源:https://stackoverflow.com/questions/44167647/terminating-all-explorer-instances-via-vba-excel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!