2013-10-17 45 views
1

我正在研究一個簡單的Word宏,它將打開一個IE頁面並顯示其位置。 該宏對Internet網頁正常工作。但是,如果網頁是本地文件,則顯示的位置始終是:空白。VBA:Internet Explorer對象不顯示正確的位置名稱

爲什麼會發生這種情況,我怎麼才能得到真正的位置? 我試過枚舉所有打開的窗口,它的作品。

但是我想知道爲什麼下面的直接方法不適用於本地頁面。

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

回答

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