如何导航到已经打开的Internet Explorer窗口? (VBA)

时间:2019-03-12 18:49:54

标签: excel vba internet-explorer

所以我一直在网上搜索有关如何执行此操作的很多信息,但似乎找不到任何具体信息。我已经看到了很多有关如何打开新的Internet Explorer窗口并导航到特定网站的示例。但是,在我的特定情况下,我希望能够简单地导航到一个已经打开的Internet Explorer窗口(这将是Internet Explorer唯一打开的窗口/选项卡)。这是因为每次打开网站时,我需要先登录才能进行任何操作。然后,理想情况下,我想将一些ID粘贴到搜索框中,然后按Enter键(我应该能够通过在线搜索来了解如何执行此操作)。

这是我到目前为止找到的内容,但是我有点迷茫,不知道如何将这部分代码按自己的意愿应用。

Sub ExplorerTest()



Const myPageTitle As String = "Wikipedia"
Const myPageURL As String = "http://en.wikipedia.org/wiki/Main_Page"
Const mySearchForm As String = "searchform"
Const mySearchInput As String = "searchInput"
Const mySearchTerm As String = "Document Object Model"
Const myButton As String = "Go"
Dim myIE As SHDocVw.InternetExplorer


With myIE.Document.forms(mySearchForm)
    'enter search term in text field
    .elements(mySearchInput).Value = mySearchTerm
    'press button "Go"
    .elements(myButton).Click
  End With

End Sub

2 个答案:

答案 0 :(得分:1)

这会同时执行所有浏览器窗口,包括Internet Explorer和Windows Explorer

Window是Internet Explorer窗口对象。

Set objShell = CreateObject("Shell.Application")
Set AllWindows = objShell.Windows
For Each window in AllWindows
    msgbox window.location
Next

或者,如果您确定这是唯一开放的地方

Set x = GetObject(,"InternetExplorer.Application")

答案 1 :(得分:1)

我尝试检查您的描述,发现您想要获取已打开的IE窗口的对象,然后尝试使其自动化。

您可以尝试参考下面的示例,这可能会对您有所帮助。

在此示例中,您可以看到使用其标题搜索已打开的页面。比起您可以使用它的对象来自动化该页面。

Sub demo()

Dim str_val As Object
marker = 0
Set objShell = CreateObject("Shell.Application")
IE_count = objShell.Windows.Count
For x = 0 To (IE_count - 1)
    On Error Resume Next
    my_url = objShell.Windows(x).document.Location
    my_title = objShell.Windows(x).document.Title

    If my_title Like "XYZ" & "*" Then
        Set IE = objShell.Windows(x)
        marker = 1
        Exit For
    Else
    End If
Next

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

Else
    MsgBox ("A matching webpage was found")

    Set str_val = IE.document.getElementById("txtbox1")
    str_val.Value = "demo text"

End If
End Sub

输出:

enter image description here

参考:

VBA code to interact with specific IE window that is already open