关闭除VBA中的1之外的所有IE窗口

时间:2016-05-22 18:40:47

标签: vba excel-vba internet-explorer excel

我使用以下代码关闭所有IE窗口。这是错误处理的一部分,当我的大型函数挂起或崩溃时,它会自动启动一个新窗口。当发生这种情况时,我想关闭所有IE窗口,除了1(我想保持最后一个窗口保持会话,因此浏览器在再次打开时不必重新进行身份验证)。

我是否可以更新下面的循环,以便关闭除最后一个窗口之外的所有IE窗口(它不会打开哪个特定的窗口,只是它打开一个)。

Function closeallIE()
        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
            Call objProcess.Terminate
        Next
        Set objProcesses = Nothing: Set objWMI = Nothing
        Debug.Print wait(3)
    End Function

2 个答案:

答案 0 :(得分:0)

您可以使用Count属性并将PID与Taskkill一起使用:

Sub closeallIE()
    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'")
    Dim j As Integer
    j = objProcesses.Count
    For Each objProcess In objProcesses
        If j > 1 Then Shell "taskkill /f /PID " & CStr(objProcess.ProcessID), vbHide

        j = j - 1
    Next
    Set objProcesses = Nothing
    Set objWMI = Nothing

End Sub

答案 1 :(得分:0)

此代码段取自HP UFT Website regarding closing browser tabs。 这可以在没有任何调整的情况下工作,并使用创建时间来关闭除最旧的选项卡以外的所有选项卡。

On error resume next

Set oDesc = Description.Create
oDesc( "micclass" ).Value = "Browser"

oDesc( "application version" ).Value = browserPropertyApplicationVersion

Set vIE= Desktop.ChildObjects(oDesc)
vIECount=vIE.count

z=vIECount
For m=1To vIECount - 1
z=z-1
    If Browser("creationtime:="&z).Exist(0) Then

            Browser("creationtime:=1").Close

    End If


If err.number > 0 Then
message = message & " @@@@@@@Error shown by application is :  " & err.description
icon_flag=0
End If
Next

Set oDesc = Nothing
Set vIE=Nothing