如何从 VBA 控制新的弹出标签

How to control new pop up tab from VBA

我写了一段代码,如果满足某些条件,它会自动下载一些文档,而我只有一个问题。单击 link 后,会打开一个新的 IE 选项卡(child 选项卡) 并且我想在一些操作后将其关闭。新标签总是有相同的标题(例如 "online.xxx")所以也许有办法控制它。

我的 parent 选项卡设置如下:

Dim IE as New ShDocVw.InternetExplorerMedium

谢谢。

要关闭现有选项卡:

Sub TestClose()

    Dim ie As Object

    Set ie = GetIEByTitle("K1000 Service Center")
    If Not ie Is Nothing Then
        ie.Quit
    End If

End Sub

根据文档标题查找打开的 IE 选项卡的功能:

Function GetIEByTitle(sTitle As String) As Object
    Dim o As Object, rv As Object
    For Each o In CreateObject("Shell.Application").Windows
        If TypeName(o) = "IWebBrowser2" Then
            If o.document.Title Like "*" & sTitle & "*" Then
                Set rv = o
                Exit For
            End If
        End If
    Next o
    Set GetIEByTitle = rv
End Function

您可以使用 Shell Windows 遍历 IE 选项卡,然后根据标题找到特殊选项卡。更多详细信息,请查看以下代码:

Sub TestClose()
    Dim IE As Object, Data As Object
    Dim ticket As String
    Dim my_url As String, my_title As String

    Set IE = CreateObject("InternetExplorer.Application")

    With IE
        .Visible = True
        .Navigate "https://amazon.com" '1st tab
        .Navigate "https://flipkart.com", CLng(2048) '2nd
        .Navigate "https://snapdeal.com", CLng(2048) '3rd

        While IE.ReadyState <> 4
            DoEvents
        Wend

        'wait some time to let page load
        Application.Wait (Now + TimeValue("0:00:05"))

        Set objShell = CreateObject("Shell.Application")
        IE_count = objShell.Windows.Count

        'loop through the window and find the tab
        For x = 0 To (IE_count - 1)
            On Error Resume Next
            'get the location and title
            my_url = objShell.Windows(x).Document.Location
            my_title = objShell.Windows(x).Document.Title

            'debug to check the value
            Debug.Print x
            Debug.Print my_title

            'find the special tab based on the title.
            If my_title Like "Amazon" & "*" Then
                Set IE = objShell.Windows(x)
                IE.Quit 'call the Quit method to close the tab.
                Exit For   'exit the for loop 
            Else
            End If
        Next

    End With
    Set IE = Nothing
End Sub