VBA IE自动化:用于打开具有相同名称和URL的多个选项卡并在其中执行相同操作的循环

时间:2017-12-20 20:16:09

标签: excel vba excel-vba internet-explorer

假设我在电子表格列中有相同网址的列表。

我手动导航到URL,然后我希望我的宏在单独的IE选项卡中打开每个URL,并单击其中的特定按钮。

我使用自定义函数FindIEObject按名称或URL抓取浏览器窗口。问题是显然每个标签都有相同的名称和URL,所以我需要找到另一种方法来区分它们并设置每个一个作为当前的IE对象。我的第一个想法是在每个标签创建时为其分配一个虚拟名称或数字。我想这个部分应该在循环中的IE.Navigate Cell.Value之后的某个地方。

这是我的代码,目前打开所有选项卡,但只在第一个中单击元素:

Private page_title As String
Public IE As InternetExplorerMedium

Sub intercept()

FindIEObject ("Allegro")

For Each Cell In Columns("A").Cells.SpecialCells(xlConstants)
    IE.Navigate Cell.Value, CLng(2049) ' open URL in new tab
    'Call MyWait
        For Each element In IE.Document.GetElementsByTagName("img")
            If element.GetAttribute("src") = "https://assets.allegrostatic.com/opbox/allegro.pl/homepage/Main%20page%20-%20new_SG_categories%20-%20icons/c4c8134ad8ae75c9d1070e7bee8cbeea.svg" Then
               element.Click
               Exit For
            End If
        Next element
Next Cell

End Sub

Sub MyWait()

Do While IE.Busy Or IE.ReadyState <> READYSTATE_COMPLETE
DoEvents
Loop
End Sub

Public Function FindIEObject(target As String) As InternetExplorerMedium
        marker = 0
        Set objShell = CreateObject("Shell.Application")
        IE_count = objShell.Windows.Count
        For x = 0 To (IE_count - 1)
            On Error Resume Next    ' sometimes more web pages are counted than are open
            page_url = objShell.Windows(x).Document.Location
            page_title = objShell.Windows(x).Document.Title
            If page_title Like target & "*" Then 'compare to find if the desired web page is already open
                Set IE = objShell.Windows(x)
                marker = 1
                Exit For
            End If
        Next

    If marker = 0 Then
        MsgBox ("A matching webpage was NOT found")
    Else
        MsgBox ("A matching webpage was found")
    End If

    End Function

我会很感激任何建议。

0 个答案:

没有答案