VBA:Internet Explorer对象未显示正确的LocationName

时间:2013-10-17 16:50:40

标签: internet-explorer vba excel-vba word-vba excel

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

为什么会这样,我怎样才能获得真实的位置? 我尝试了枚举所有打开窗口的技巧,但它确实有效。

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

操作系统: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

1 个答案:

答案 0 :(得分:0)

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

通过在Shell Windows中循环,您可以找到并重新分配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