首页 > 解决方案 > Excel VBA 错误:对象变量或未设置块变量

问题描述

运行 Excel 宏 VBA 时遇到错误。它说:对象变量或未设置块变量

Private Sub CommandButton1_Click()
Dim ie As InternetExplorer
Dim doc As HTMLDocument
Dim rating As String

Set ie = New InternetExplorer

With ie
    .navigate "https://www.pse.com.ph/company-information-JFC/"
    .Visible = False
    Do While .readyState <> 4: DoEvents: Loop

    Set doc = ie.document

    With doc
        rating = .getElementsByClassName("last-price")(0).PreviousSibling.getElementsByTagName("h3")(0).innerText
        MsgBox rating
    End With

End With

ie.Quit

End Sub

Excel在这里指出我:

rating = .getElementsByClassName("last-price")(0).PreviousSibling.getElementsByTagName("h3")(0).innerText

我浏览 Microsoft 文档。他们告诉我的变量没有设置。虽然乍一看,我的代码看起来不错。

请指教。

标签: excelvbaweb-scraping

解决方案


您要查找的内容位于 iframe 中。您可以直接导航到 iframe 中的 url,或者从帖子中的 url 开始,然后按照该 iframe 中的 url 访问内容。

使用 IE(从您帖子中的网址开始):

Private Sub FetchPrice()
    Dim targetUrl$

    With CreateObject("InternetExplorer.Application")
        .Visible = False
        .navigate "https://www.pse.com.ph/company-information-JFC/"
        Do While .readyState <> 4: DoEvents: Loop
        targetUrl = .document.getElementById("company_infos").getAttribute("src")
        .navigate targetUrl
        Do While .readyState <> 4: DoEvents: Loop
        MsgBox .document.querySelector("h3.last-price").innerText
        .Quit
    End With
End Sub

如果您希望直接使用 iframe 中的内容 url 获取价格,您可以使用 xhr(直接使用 iframe 中的 url):

Sub GetPrice()
    Const URL$ = "https://frames.pse.com.ph/security/jfc"
    Dim Html As HTMLDocument
    
    Set Html = New HTMLDocument

    With CreateObject("MSXML2.XMLHTTP")
        .Open "Get", URL, False
        .setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36"
        .send
        Html.body.innerHTML = .responseText
        
        MsgBox Html.querySelector("h3.last-price").innerText
    End With
End Sub

在这两种情况下,我从以下元素中定位价格:

<div class="col-12 align-items-center px-0 font-weight-bolder">
    <h3 class="last-price">194.00</h3>
</div>

推荐阅读