2011-09-02

Accessing IE from vbScript

It used to be simple to use Internet Explorer as output for vbScripts. Here is a sample script that opened a custom HTML page and then writes something into a <div id="Status">...</div> stanza.

Dim objIE
Set objIE = WScript.CreateObject ("InternetExplorer.Application")
objIE.Width = 700
objIE.Height = 250
objIE.Toolbar = false
objIE.statusbar = false
objIE.Navigate "D:\Test\Output.html"
objIE.Visible = true
objIE.document.all.Status.InnerHTML = "<font color='#0063FF'><b>Done... waiting 5 secs...</b></font>"
WScript.Sleep (5000)
objIE.Quit


Now with Windows 7 and IE 9 many of those scripts do no longer run but throw errors. Common errors are for example: "The object invoked has disconnected from its client." (80010108) or "Unspecified error" (80004005)

It seems that the original Internet Explorer object gets lost because the web page is loaded into a child process of IE. So any reference to it from a vbScript fails.

A few changes to the above script can work around that issue. It may not be the most elegant but it is working so far.

Dim objIE
Set objIE = WScript.CreateObject ("InternetExplorer.Application")
Set objShellApp = CreateObject("Shell.Application")
objIE.Width = 700
objIE.Height = 250
objIE.Toolbar = false
objIE.statusbar = false
objIE.Navigate "D:\Test\Output.html"
objIE.Visible = true
Set objIE = Nothing
For Each objWindow In objShellApp.Windows
If LCase(objWindow.LocationName) = LCase("Output.html") Then
Set objIE = objWindow
End If
Next
objIE.document.all.Status.InnerHTML = "<font color='#0063FF'><b>Done... waiting 5 secs...</b></font>"
WScript.Sleep (5000)
objIE.Quit

Basically we are looping through all windows and connect (hopefully ;-) ) to the one that has our HTML file open.