excel - 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 文档。他们告诉我的变量没有设置。虽然乍一看,我的代码看起来不错。
请指教。
解决方案
您要查找的内容位于 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>
推荐阅读
- r - R - 用来自另一个矩阵的特定数据块的数据填充矩阵
- ios - iOS 11 prefersLargeTitles 在方向更改后不扩展
- javascript - 重新加载 Puppeteer => page.setCookie(...cookies) 后 Cookies 消失了
- llvm - LLVM 中的 OpaqueType::get() 函数
- matlab - 在matlab中读取具有可变条目数的文本文件
- ruby - 检查 Ruby 代码中的命令行参数是否存在
- c# - 在 connectionString 中添加新连接
- backup - 使用命令行工具备份 STM32 固件
- python - 使用 Pandas 按组有条件地偏移值
- eclipse-plugin - 在 Eclipse WizardPage 中 - 在页面之间导航的问题