我写了一个VBA代码,以便我可以在工作中废弃我公司的 Intranet 中的数据。
的问题:
当我运行代码时,会发生以下错误。
Run-time error '91':
object variable or with block variable not set
它出现在下面的代码行中。
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
答案 0 :(得分:2)
在访问任何元素之前,您需要等待文档完全呈现并且DOM可用。页面连接并开始加载后ie.ReadyState
更改为READYSTATE_COMPLETE
。您的代码在调试时工作的原因是您在几秒钟内开始使用调试器,页面完成加载。
With ie
.Visible = True
.Navigate "www.example.com/product/" & Cells(r, "B").Value
Do Until .ReadyState = READYSTATE_COMPLETE
DoEvents
Loop
Do Until .Document.ReadyState = "complete"
DoEvents
Loop
End With
我还建议您至少在开发过程中使窗口可见。一旦完成功能并进行调试,就可以使窗口不可见。请记住,如果您在代码完成后忘记关闭隐藏的IE窗口,您的用户将最终失控iexplore.exe进程。
答案 1 :(得分:0)
如果您只想忽略错误并继续下一次迭代,请使用此修改后的代码:
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
'Edit:
myPoints = ""
On Error Resume Next
myPoints = Trim(Doc.getElementsByName("price")(0).getAttribute("value"))
On Error Goto 0
Cells(r, "C").Value = myPoints
Next r
End Sub
答案 2 :(得分:0)
您还可以循环播放,直到设置了元素(还添加一个超时子句)
my.metric.$aggregation