2014-09-12 19 views
1

工作,我想從網站&獲取數據的網頁按鈕互動把它在Excel工作表上使用Excel VBA只在步調試模式

場景: 網頁包含使用id = btnAllRun按鈕。

當我點擊按鈕時,表格會動態生成,其中包含tr標籤中的信息。 使用宏我需要計數沒有。這樣的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 

當我試圖運行宏時得到「對象變量或與沒有設置塊」運行在步調試模式相同的宏我得到正確的結果,當

任何幫助,將不勝感激!

回答

2

如果它在調試模式下工作,那麼這意味着您的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 
+0

謝謝Siddhart :)這就是我正在尋找! – Droidwala 2014-09-15 07:11:43