VBA: 将 HTML 设置为 Internet Explorer 对象错误

VBA: set HTML as Internet Explorer object ERROR

我正在尝试从 VBA 的网站获取内容,但我总是收到错误消息。

我已经尝试过其他几种方法来研究类似的问题,但似乎没有任何效果...我也尝试过 set ie = New InternetExplorer,但也没有效果

你能帮帮我吗?我的目标是进一步找到一个特定的关键字并统计它出现的次数。

谢谢, M

Sub website()

Dim ie As Object
Dim ht As HTMLDocument

Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = False

ie.navigate ("https://poetenalinha.pt/2021/01/13/gratinado-de-massa-com-peru-e-legumes/")

Set ht = ie.document --> here is the error!!

Set elems = ht.getElementsByClassName("entry-content")

For Each elem In elems
    Debug.Print (elem.innerText)
    
Next

End Sub

这对我有用 - 由于某种原因,ie 对象与浏览器实例断开连接。如果您重新建立连接(使用“GetIE”功能),它会起作用。

Sub website()

    Dim ie As Object, elems, elem
    Dim ht As HTMLDocument
    
    Set ie = CreateObject("InternetExplorer.Application")
    ie.Visible = True
    
    ie.navigate "https://poetenalinha.pt/2021/01/13/gratinado-de-massa-com-peru-e-legumes/"

    Application.Wait Now + TimeSerial(0, 0, 10) ' wait 10 sec
    
    Set ie = GetIE("https://poetenalinha.pt")   ' "reconnect" to IE object
    Set ht = ie.document
    
    Set elems = ht.getElementsByClassName("entry-content")
    
    For Each elem In elems
        Debug.Print (elem.innerText)
    Next

End Sub

'get a reference to an existing IE window, given a partial URL
Function GetIE(sLocation As String) As Object

    Dim objShell As Object, objShellWindows As Object, o As Object
    Dim sURL As String
    Dim retVal As Object

    Set retVal = Nothing
    Set objShell = CreateObject("Shell.Application")
    Set objShellWindows = objShell.Windows

    For Each o In objShellWindows
        sURL = ""
        On Error Resume Next  'because may not have a "document" property
        'Check the URL and if it's the one you want then
        ' assign the window object to the return value and exit the loop
        sURL = o.document.Location
        On Error GoTo 0
        If sURL Like sLocation & "*" Then
            Set retVal = o
            Exit For
        End If
    Next o

    Set GetIE = retVal

End Function

进入网站后需要等待IE完全加载。完整代码如下,运行良好:

Sub website()

Dim ie As Object
Dim ht As HTMLDocument

Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = True

ie.navigate ("https://poetenalinha.pt/2021/01/13/gratinado-de-massa-com-peru-e-legumes/")

'add this part
Do Until ie.readyState = 4
   DoEvents
Loop
    
Set ht = ie.document

Set elems = ht.getElementsByClassName("entry-content")

For Each elem In elems
    Debug.Print (elem.innerText)
    
Next

End Sub

结果: