VBA代码 – 卡在第四循环

我有一个代码,应该打开一个网站,select一个位置,将HTML表格复制到Excel工作表,并在另一个位置重复。 但是当我尝试运行“For”循环时,在第四次迭代时出现错误。 消息说:“对象variables或块variables未设置”。 debugging工具指向44行

Sub ParseTable() Dim IE As InternetExplorer Dim htmldoc As MSHTML.HTMLDocument 'Document object Dim eleColtr As MSHTML.IHTMLElementCollection 'Element collection for tr tags Dim eleColtd As MSHTML.IHTMLElementCollection 'Element collection for td tags Dim eleRow As MSHTML.IHTMLElement 'Row elements Dim eleCol As MSHTML.IHTMLElement 'Column elements Dim ieURL As String 'URL Dim x As Integer Dim y As String y = "A1" For x = 1 To 4 If x <> 2 Then 'Skip iteration 2 Set IE = New InternetExplorer IE.Visible = True Application.ScreenUpdating = False ieURL = "***" IE.navigate ieURL 'Wait Do While IE.Busy Or IE.readyState <> 4 DoEvents Loop Set htmldoc = IE.document 'Document webpage Do While IE.Busy Or IE.readyState <> 4 DoEvents Loop IE.document.getElementById("ddlLevel1").selectedIndex = x IE.document.getElementById("ddlLevel1").FireEvent ("onchange") Do While IE.Busy Or IE.readyState <> 4 DoEvents Loop Set eleColtr = IE.document.getElementsByTagName("tr") 'Find all tr tags 'This section populates Excel i = 0 'start with first value in tr collection For Each eleRow In eleColtr 'for each element in the tr collection Set eleColtd = IE.document.getElementsByTagName("tr")(i).getElementsByTagName("td") 'get all the td elements in that specific tr j = 0 'start with the first value in the td collection For Each eleCol In eleColtd 'for each element in the td collection Sheets("Sheet1").Range(y).Offset(i, j).Value = eleCol.innerText 'paste the inner text of the td element, and offset at the same time j = j + 1 'move to next element in td collection Next eleCol 'rinse and repeat i = i + 1 'move to next element in td collection Next eleRow 'rinse and repeat Sheets("Sheet1").Range(y).Offset(i, 0).Select y = "A" & ActiveCell.Row IE.Quit End If Next x Application.ScreenUpdating = True End Sub 

不知道可能的原因是什么。 我在Excel工作表上从前4个位置(减去位置2)获得表格。 赦免我长期低效的代码(我自己不是程序员)。 我使用的网页需要login并拥有机密数据,但我会尽量提供input。 提前感谢任何帮助!

我看到这发生在很多例子,试图等待IE.Busy进一步处理之前。 问题是文档模型还没有完全形成,所以你得到一个错误,试图访问对象模型中的元素。

最安全的方法是实际循环,直到对象存在 – 即。 如果你知道它会出现在每个文件中。 如果您想安全玩游戏,您可以在停止之前添加对您执行的检查次数的限制并显示错误消息。

将其添加到模块的顶部

 Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) 

然后replace这一行(如果是问题行)

 Set eleColtr = IE.document.getElementsByTagName("tr") 

用这个轻微的Delay和DoEvents – 然后循环来检查你的tr元素

 DoEvents Sleep 1000 ' delay once second Do DoEvents Sleep 500 ' delay half a second Loop Until not IsNull(IE.document.getElementsByTagName("tr")) 

如果进入无限循环,找不到你的tr元素,你可以在尝试次数上加一个计数器

我也会在每个循环的开始处添加一个延迟

之后For Each eleRow In eleColtr添加Sleep 500