Terminating all instances of explorer via VBA - Excel

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 all instances of Explorer before running some functions that fetch data from web servers, but I ran into an issue where it tries to close an open browser with multiple tabs. If the user only opens one IE window (one tab), then he closes it just fine and moves; if this user has multiple windows open separately (not nested in one window), then he closes them all just fine and moves on; but for some reason, if one window is open with multiple tabs, I get a runtime error "-2147217406 (80041002)": "Not found". Any help helping with this would be greatly appreciated.

+3


source to share


2 answers


Not exactly what you asked, but a different 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

      

+1


source


This issue is caused by the way IE handles tabs. There is 1 main instance of IE and a new iexplore process is created for each tab. Therefore, when the main host instance is closed, all processes associated with tabs are closed. This is throwing an error in your code because the collection you are enumerating is a snapshot from an earlier state, and you are trying to close existing processes. This can be seen in the TaskManager.

Now answer how to improve your code (of course, simply mistakenly resuming the following would also help, but exiting after the first closed instance might not be enough if the user opened more sessions):



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

      

0


source







All Articles