与使用excel vba的网页上的button交互只在步骤debugging模式下工作

我试图从网站获取数据,并把它放在Excel工作表

场景:网页包含id = btnAllRun的button。

当我点击button时,表格会dynamic生成,其中包含tr标签中的信息。 使用macros我需要计数没有。 这样的tr标签,并把计数在工作表中。

码:

Dim IE as Object Sub Button_Click() Set IE = CreateObject("InternetExplorer.Application") IE.Visible = True IE.Navigate URL Do DoEvents Loop Until IE.ReadyState = 4 //waiting for the webpage to load Set Elmt = IE.Document.getElementById("btnAllRun") //get button elmt for All Running Elmt.Click //Clicking button Do DoEvents Loop Until IE.ReadyState = 4 Set Tbl = IE.Document.getElementById("gvRunning") //gets table elmt containing tr tags Sheets("XXX").Range("B36") = Tbl.Rows.Length - 1 

当我试图运行macros我得到'对象variables或块未设置', 在步骤debugging模式下运行相同的macros我得到正确的结果。

任何帮助,将不胜感激!

如果它在debugging模式下工作,那么这意味着您的DoEvents不能按预期工作。 在这种情况下,我使用定制的例程Wait 。 所以我正在做的是迫使代码等待一段时间,然后继续。 对于较慢的系统,您可能需要增加时间。

Wait 2基本上暂停代码2秒。

尝试这个。 这已经在很多场合为我工作了。

 Dim IE As Object Sub Button_Click() Set IE = CreateObject("InternetExplorer.Application") IE.Visible = True IE.Navigate URL Do While IE.ReadyState <> 4: DoEvents: Loop Wait 2 Set Elmt = IE.Document.getElementById("btnAllRun") Wait 2 Elmt.Click Do While IE.ReadyState <> 4: DoEvents: Loop Wait 2 Set Tbl = IE.Document.getElementById("gvRunning") Sheets("XXX").Range("B36") = Tbl.Rows.Length - 1 ' '~~> Rest of the code ' End Sub Private Sub Wait(ByVal nSec As Long) nSec = nSec + Timer While nSec > Timer DoEvents Wend End Sub