1

我正在研究下面的一个简单的 Word 宏,它打开一个 IE 页面并显示它的位置。该宏适用于 Internet 网页。但是,如果网页是本地文件,则显示的位置始终为 about:blank。

为什么会发生这种情况,我怎样才能获得真实位置?我尝试了枚举所有打开的窗口的技巧并且它有效。

但是我想知道为什么下面的直接方法不适用于本地页面。

操作系统:Windows 7 + IE8

Option Explicit

Dim oIE

Sub Macro()

    Set oIE = CreateObject("InternetExplorer.Application")

    oIE.navigate "about:blank"

    oIE.Top = 0
    oIE.Left = 0
    oIE.Width = 500
    oIE.Height = 500

    oIE.navigate "C:\test\test.htm"

    oIE.Visible = 2

    Do While (oIE.Busy)
        DoEvents
    Loop

    MsgBox oIE.LocationName

    Set oIE = Nothing

End Sub
4

1 回答 1

0

在我的测试中,Internet Explorer 对象在加载后会自行分离...

通过循环通过 Shell 窗口,您可以找到并重新分配 IE 对象。完成此操作后,我就可以成功查询 LocationName

请参阅下面的测试例程:

Sub Macro()
Dim oIE, oShell, objShellWindows, strPath, X

    strPath = "C:\test\test.htm"

    Set oIE = CreateObject("InternetExplorer.Application")

    'oIE.navigate "about:blank"
    oIE.Top = 0
    oIE.Left = 0
    oIE.Width = 500
    oIE.Height = 500

    oIE.navigate strPath

    Do While oIE.Busy And oIE.ReadyState < 2
        DoEvents
    Loop

    MsgBox oIE.LocationName & vbCrLf & oIE.LocationURL

    Set oShell = CreateObject("WScript.Shell")
    Set objShellWindows = CreateObject("Shell.Application").Windows
    For X = objShellWindows.Count - 1 To 0 Step -1
        Set oIE = objShellWindows.Item(X)
        If Not oIE Is Nothing Then
          '  Uncomment below line to troubleshoot
          '  MsgBox oIE.LocationName & vbCrLf & oIE.LocationURL
            If StrComp(oIE.LocationURL, "file:///" & Replace(strPath, Chr(92), "/", 1, -1, 1), 1) = 0 Then
                Do While oIE.Busy And oIE.ReadyState < 2
                    DoEvents
                Loop
                oIE.Visible = 2
                Exit For
            End If
        End If
        Set oIE = Nothing
    Next
    Set objShellWindows = Nothing
    If oIE Is Nothing Then
        MsgBox "Could Not Find The IE Window"
    End If

    MsgBox oIE.LocationName & vbCrLf & oIE.LocationURL

    Set oIE = Nothing

End Sub
于 2013-10-17T18:28:39.200 回答