以下のコードは、最初の実行時には機能しますが、その後の実行では失敗することがよくあります。失敗した行は以下にコメントされています。SHDocVw.ShellWindows をループすると問題が発生し、再度実行する前に何かをクリーンアップする必要があると思います。問題を再現するには、IE で Google を開き、この手順を繰り返します。助けてくれてありがとう。正確なエラーは Exception from HRESULT: 0x800A01B6 です。(これは、IE_test が設定されている場合に実際に何度も再利用する、より複雑なコードの単純化されたバージョンであることに注意してください。)
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