Search code examples
ms-accessvbainternet-explorer-11

VBA - losing control of internet exploror


I have a function that loads a website prompting a user to login. This works on everyone's computers except one person and I cannot figure it out. I get a runtime error on the line Do Until ieApp.ReadyState = 4: DoEvents: Loop that reads "Automation error. The object invoked has disconnected from its clients."

Function Firewall_Login() As Boolean
    Dim ieApp As Object
    Dim ieDoc As Object
    Dim ieTable As Object
    Dim ieDocResult As Object
    Dim start_time

    Set ieApp = CreateObject("internetexplorer.application")
    start_time = Now()

    ieApp.Navigate "http://awebsite.com/"
    Do While ieApp.ReadyState = 4: DoEvents: Loop
    Do Until ieApp.ReadyState = 4: DoEvents: Loop 'errors here just on the one computer

    Set ieDoc = ieApp.Document
    ...
   'do some stuff
    ...

    ieDoc.Close
    Set ieDoc = Nothing

    ieApp.Quit
    Set ieApp = Nothing
    Firewall_Login = True
End Function

Seems like the object ieApp simply loses the instance of IE and can't do anything. Anyone have any suggestions?

All users are on the same version of IE -- 11.0.9600.18816


Solution

  • This code is taken from my blog. The code loops through shell windows looking to match the title bar which for IE will be the url. This way the reference is reacquired. Sometimes the reference can be lost due to a change of security zone etc.

    Option Explicit
    
    '* Tools - References
    '*      MSHTML      Microsoft HTML Object Library                   C:\Windows\SysWOW64\mshtml.tlb
    '*      SHDocVw     Microsoft Internet Controls                     C:\Windows\SysWOW64\ieframe.dll
    '*      Shell32     Microsoft Shell Controls And Automation         C:\Windows\SysWOW64\shell32.dll
    
    Private Function ReacquireInternetExplorer(ByVal sMatch As String) As Object
        Dim oShell As Shell32.Shell: Set oShell = New Shell32.Shell
        Dim wins As Object: Set wins = oShell.Windows
        Dim winLoop As Variant
        For Each winLoop In oShell.Windows
            If "C:\Program Files (x86)\Internet Explorer\IEXPLORE.EXE" = winLoop.FullName Then
    
                Dim sFile2 As String
                sFile2 = "file:///" & VBA.Replace(sMatch, "\", "/")
                If StrComp(sFile2, winLoop.LocationURL, vbTextCompare) = 0 Then
                    Set ReacquireInternetExplorer = winLoop.Application
                    GoTo SingleExit
                End If
            End If
        Next
    SingleExit:
    End Function