【问题标题】:Excel VBA Error: Object variable or With block variable not setExcel VBA 错误:对象变量或未设置块变量
【发布时间】:2021-10-15 09:03:17
【问题描述】:

运行 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 文档。他们告诉我的变量没有设置。虽然乍一看,我的代码看起来不错。

请指教。

【问题讨论】:

  • 要么没有“last-price”类的元素,要么有,但第一个没有PreviousSibling,或者那个兄弟确实存在,但是没有 H3 子元素。都是一行,因此很难知道问题出在哪里:如果将其分解,则更容易排除故障。
  • 看看那个页面,它在 IE 中被严重破坏了,所以也许你没有找到你要找的东西也就不足为奇了。

标签: excel vba web-scraping


【解决方案1】:

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

使用 IE(从帖子中的 url 开始):

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>

【讨论】:

  • 谢谢!你给的这两个选项工作! :) 没有意识到它在 iframe 中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-01
  • 1970-01-01
相关资源
最近更新 更多