在清理我的InternetExplorer
实例时,这是返回HTMLDocument
的有效方法吗?
Private Function myFunction() As HTMLDocument
'init
Dim out As HTMLDocument
Dim browser As InternetExplorer
Set browser = CreateObject("InternetExplorer.Application")
...
'get HTMLDocument
Set out = browser.document
browser.Quit
Set browser = Nothing
Set myfunction = out
Exit Function
我之所以这么问,是因为我稍后在代码中使用返回的HTMLDocument
时会出现一些古怪的行为。我会看到输出003
,但不会看到004
:
doc = myFunction()
...
Debug.Print "003"
strVar = doc.getElementsByClassName("sectionheading_center")(0).innerText
Debug.Print "004"
....
错误:-2147417848-Automation error The object invoked has disconnected from its clients. -VBAProject-1000440-0
您将失去动态交互,但可以通过将innerHTML传输到MSHTML来获取html。HTMLDocument变量。它也只是正文html。
Private Function myFunction() As MSHTML.HTMLDocument
'init
Dim out As MSHTML.HTMLDocument
Dim browser As SHDocVw.InternetExplorer
Set browser = New SHDocVw.InternetExplorer
'...Other code
'get HTMLDocument
Set out = New MSHTML.HTMLDocument
out.body.innerHTML = browser.Document.innerHTML
browser.Quit
Set myFunction = out
Exit Function
@KostasK的类解决方案是维护实例化实例以及向该对象添加方法的好方法。