請問為何以下兩段不同程式碼在 ie8 均可正常執行,但 ie11 卻無反應(標示處),是否因為程式寫法不同或需要加入什麼物件呢?
Sub test()
Dim p As Object
Set myIE = CreateObject("InternetExplorer.Application")
With myIE
.Visible = True
.Navigate "http://test/Default.aspx" '公司內網故無法提供真實網址
Do While Busy Or .ReadyState <> 4: DoEvents: Loop
Set p = .Document.all.tags("INPUT") '無反應
.Document.all.txtUsername.innerText = "test" '無反應
.Document.all.txtPassword.innerText = "test" '無反應
.Document.all.ImageButton2.Click '無反應
Do While Busy Or .ReadyState <> 4: DoEvents: Loop
Sub test()
Set myIE = CreateObject("InternetExplorer.Application")
With myIE
.Visible = True
.Navigate "http://test/Report_OMS/Reprt_Sale.aspx" '公司內網故無法提供真實網址
Do While Busy Or .ReadyState <> 4: DoEvents: Loop
.Document.all("ReportViewer1ctl01ctl05ctl00").Value = "Excel" '無反應
End With
End Sub
這應該是IE 11有較高的安全性設定所致。
原因可以參考:
簡單的說,在執行Navigate
方法之後,IE會在瞬間關閉後重開並連線到指定網址,導致myIE
所指向的物件已經被消滅。
上方的stackoverflow提供二種解法:
你的VBA我改寫如下:
Sub test()
Dim p As Object, myIE as object, Shell as object, eachWindow as object
Set myIE = CreateObject("InternetExplorer.Application")
With myIE
.Visible = True
.Navigate "http://test/Default.aspx" '公司內網故無法提供真實網址
End With
' 主要加入以下區塊
' ===============================
If LCase(Typename(myIE)) = "object" then
Set Shell = CreateObject("Shell.application")
For Each eachWindow In Shell.Windows
If instr(eachWindow.LocationURL, URL) <> 0 Then
Set myIE = eachWindow
Exit For
End If
Next eachWindow
End If
' ===============================
With myIE
Do While .Busy Or .ReadyState <> 4: DoEvents: Loop
Set p = .Document.all.tags("INPUT")
.Document.all.txtUsername.innerText = "test"
.Document.all.txtPassword.innerText = "test"
.Document.all.ImageButton2.Click
Do While .Busy Or .ReadyState <> 4: DoEvents: Loop
End With
End Sub
document.all指令太舊了
建議改用document.getelementsbyname或document.getelementsbyid