VBA – 在内部网上抓取网页

我写了一个VBA代码,这样我就可以在公司的内部网上取消数据。

问题:

当我运行代码时,发生下面的错误。

Run-time error '91': object variable or with block variable not set 

它发生在下面的代码行上。

 myPoints = Trim(Doc.getElementsByName("price")(0).getAttribute("value")) 

当我debugging它并逐行运行时,它可以检索所有的值。

可能是我错过了一个error handling程序?

input和输出:

我在列B上input多个产品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 

在访问任何元素之前,您需要等待文档完全呈现并且DOM可用。 ie.ReadyState一旦页面连接并开始加载, READYSTATE_COMPLETE就会更改为READYSTATE_COMPLETE 。 debugging时代码工作的原因是在几秒钟内开始使用debugging器,页面完成加载。

 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 

我也build议你至less在开发的时候让IE窗口可见。 一旦完成了function并进行了debugging,就可以使窗口不可见。 请记住,如果你忘记closures你的代码完成后,不可见的IE窗口,你的用户将最终失控iexplore.exe进程。

如果您只想忽略错误并继续下一次迭代,请使用以下修改的代码:

 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