如何使用VBA拦截和操作Internet Explorer弹出窗口

时间:2013-01-21 20:47:46

标签: internet-explorer vba dom automation popup

语言/软件:

语言是VBA。该应用程序是Access 2003(我也可以使用Excel)和Internet Explorer(在Windows XP / Seven上)。

问题:

我正在开发一个Access宏,它打开并操作我工作的企业的Intranet站点。

我可以创建新的IE窗口并填写表单中的数据,但我需要能够拦截和操作其他IE窗口,例如弹出窗口,当我点击链接时打开,当我选择一个选项时选择元素或加载页面时。

1 个答案:

答案 0 :(得分:5)

这是我用来从它的标题中获取IE窗口的一些代码。它分为两个函数,因为我的一个用户遇到了一个非常奇怪的问题,即没有正确捕获错误。您可能(可能会)将私有函数的主体移动到公共函数中。

此外,您需要设置对Microsoft Internet Controls的引用(这是shdocvw.dll或ieframe.dll,具体取决于您的Windows版本),我建议您将对Microsoft HTML Object Library的引用设置为一旦拥有IE对象,就可以更轻松地遍历DOM。

Function oGetIEWindowFromTitle(sTitle As String, _
                               Optional bCaseSensitive As Boolean = False, _
                               Optional bExact As Boolean = False) As SHDocVw.InternetExplorer

    Dim objShellWindows As New SHDocVw.ShellWindows
    Dim found As Boolean
    Dim startTime As Single

    found = False
    'Loop through shell windows
    For Each oGetIEWindowFromTitle In objShellWindows
        found = oGetIEWindowFromTitleHandler(oGetIEWindowFromTitle, sTitle, bCaseSensitive, bExact)
        If found Then Exit For
    Next

    'Check whether a window was found
    If Not found Then
        Set oGetIEWindowFromTitle = Nothing
    Else
        pauseUntilIEReady oGetIEWindowFromTitle
    End If

End Function

Private Function oGetIEWindowFromTitleHandler(win As SHDocVw.InternetExplorer, _
                                      sTitle As String, _
                                      bCaseSensitive As Boolean, _
                                      bExact As Boolean) As Boolean

    oGetIEWindowFromTitleHandler = False

    On Error GoTo handler
    'If the document is of type HTMLDocument, it is an IE window
    If TypeName(win.Document) = "HTMLDocument" Then
        'Check whether the title contains the passed title
        If bExact Then
            If (win.Document.title = sTitle) Or ((Not bCaseSensitive) And (LCase(sTitle) = LCase(win.Document.title))) Then oGetIEWindowFromTitleHandler = True
        Else
            If InStr(1, win.Document.title, sTitle) Or ((Not bCaseSensitive) And (InStr(1, LCase(win.Document.title), LCase(sTitle), vbTextCompare) <> 0)) Then oGetIEWindowFromTitleHandler = True
        End If
    End If
handler:
    'We assume here that if an error is raised it's because
    'the window is not of the correct type. Therefore we
    'simply ignore it and carry on.

End Function

使用上面的代码如下:

Sub test()

    Dim ie As SHDocVw.InternetExplorer
    Dim doc As HTMLDocument 'If you have a reference to the HTML Object Library
    'Dim doc as Object 'If you do not have a reference to the HTML Object Library

    ' Change the title here as required
    Set ie = oGetIEWindowFromTitle("My popup window")
    Set doc = ie.Document

    Debug.Print doc.getElementsByTagName("body").Item(0).innerText

End Sub

您几乎可以从窗口的任何属性中找到一个窗口,或者它的文档内容。如果你正在努力解决这个问题,请评论:)。