Sometimes Unable to get .Document.Body.InnerHtml
-
24-06-2021 - |
Question
The code below works the first time it is run but often fails on subsequent runs. The line where it fails is commented below. I think that looping through SHDocVw.ShellWindows creates the issue and I need to clean up something before running it again. To duplicate the issue, Open google in IE and then run this procedure, repeat. Thanks for any help. The exact error is Exception from HRESULT: 0x800A01B6 . (Note that this is a simplified version of more complex code where I actually do reuse IE_test many times if it's set.)
Public IE_test As SHDocVw.InternetExplorer
Sub TestIE()
Dim shellWindows_3 As New SHDocVw.ShellWindows()
Dim htmlDoc As String
Dim link1 = "google.com"
If IsNothing(IE_test) = True Then
For Each ie_x As SHDocVw.InternetExplorer In shellWindows_3
If ie_x.LocationURL.Contains(link1) Then 'find the google instance
IE_test = ie_x
End If
Next
End If
With IE_test
.Visible = True
htmlDoc = .Document.Body.InnerHtml 'Fails here on second run
.Quit()
End With
IE_test = Nothing
MsgBox(Len(htmlDoc))
End Sub
Solution
I ended up solving this issue by completely removing .Quit() from any procedure (until the program closes). Now, I am always reusing the existing instances of IE rather than closing and reopening which is what allows the error to be avoided.