【发布时间】:2015-01-09 16:44:31
【问题描述】:
我编写了一个 VBA 代码来从我公司的 Intranet 中抓取数据。
问题:
出现以下错误:
运行时错误“91”:
对象变量或未设置块变量
它发生在:
myPoints = Trim(Doc.getElementsByName("price")(0).getAttribute("value"))
当我调试它并逐行运行时,它可以检索所有值。
输入和输出:
我在 B 列输入多个产品 ID 并在 C 列检索数据:
B 列 = 产品 ID
C 列 = 价格
HTML:
<td id="myPower_val_9" style="visibility: visible;">
<input type="text" disabled="disabled" value="300" name="price"></input>
</td>
VBA:
Sub Button1_Click()
Dim ie As Object
Dim r As Integer
Dim myPoints As String
Dim Doc As HTMLDocument
Set ie = New InternetExplorerMedium
For r = 2 To Range("B65535").End(xlUp).Row
With ie
.Visible = 0
.navigate "www.example.com/product/" & Cells(r, "B").Value
Do Until .readyState = 4
DoEvents
Loop
End With
Set Doc = ie.document
myPoints = Trim(Doc.getElementsByName("price")(0).getAttribute("value"))
Cells(r, "C").Value = myPoints
Next r
End Sub
我错过了错误处理程序吗?
【问题讨论】:
-
您是调试了整个循环还是仅调试了一次迭代?对于单次迭代,网页可能不包含所需的元素。尝试设置 ie.visible=true 并在出现错误时分析网页。
-
@silentsurfer 我循环了整个代码,它只发生在那一行。我在家里尝试了我们雅虎金融(互联网)上的类似代码,它工作正常。我可以添加任何错误处理程序来修复代码吗?
标签: excel vba web-scraping intranet