2017-02-21 172 views
1

我似乎陷入了一個奇怪的問題。我有下面的Excel VBA代碼來訪問一個網站並輸入一個用戶ID(來自表1中的用戶ID列A),然後檢索在點擊提交按鈕後顯示的用戶名,然後繼續其餘的用戶ID。Excel VBA多個For循環不工作

Public Sub TEST() 
TestPage = "http://test.com/" 

Dim IE As New InternetExplorer 
Dim Doc As HTMLDocument 
Dim GetElem As Object 
Dim GetElem2 As Object 

IE.Visible = True 
IE.navigate TestPage 
Do 
    DoEvents 
Loop Until IE.readyState = READYSTATE_COMPLETE 
Application.Wait (Now + TimeValue("0:00:04")) 

Set Doc = IE.document 
CurRow = Sheet1.UsedRange.Rows.Count 

Do While CurRow > 0 
    Application.Wait (Now + TimeValue("0:00:4")) 

    'Find/Get the userID textbox and enter the current userID 
    For Each GetElem In Doc.getElementsByTagName("input") 
     If GetElem.ID = "query" Then 'I could just do getElementByID later 
      GetElem.Value = Sheet1.Range("A" & CurRow).Value 
     End If 
    Next 

    'Find and click the submit button   
    For Each GetElem2 In Doc.getElementsByTagName("button") 
     If GetElem2.Type = "submit" Then 
      GetElem2.Click 
      Application.Wait (Now + TimeValue("0:00:03")) 
     End If 
    Next 
    CurRow = CurRow - 1 
Loop 
End Sub 

問題是代碼只能工作一次。它將第一個用戶標識輸入文本框並點擊提交。當它循環並嘗試輸入下一個用戶ID時,代碼會陷入循環。

如果我刪除整個2nd For-Next循環,它將起作用(儘管它不提交,它會在文本框中輸入每個用戶標識)。

最重要的是,如果我使用F8調試代碼一步一步,一切工作正常。只有讓問題時,完全運行的代碼。:(

+0

放了'debug.print CurRow'了'Loop'前,並檢查它在即時窗口給的值。 – Vityata

+0

它死循環。 CurRow總是大於零,每次它通過時,都會重新啓動「For Each GetElem In Doc.getElementsByTagName(」input「)」 - 因此它總是會在第一個實例中運行 - 每個循環都需要試着把所有的.query名字先放到數組中,然後用i = lbound(myArray)來綁定(myArray) –

+0

我不明白:(我可以看到你的'你可能會看到這個問題,但是我在這裏撓撓腦袋,爲什麼你說CurRow總是大於零?我的意思是CurRow從表單開始1.usedrange.rows.count是78,那麼它每次在Do-While循環中循環時減1 – jay

回答

0
Public Sub TEST() 
TestPage = "http://test.com/" 

Dim IE As New InternetExplorer 
Dim Doc As HTMLDocument 
Dim GetElem As Object 
Dim GetElem2 As Object 

IE.Visible = True 
IE.navigate TestPage 
Do 
    DoEvents 
Loop Until IE.readyState = READYSTATE_COMPLETE 
Application.Wait (Now + TimeValue("0:00:04")) 

Set Doc = IE.document 
CurRow = Sheet1.UsedRange.Rows.Count 

    For Each GetElem In Doc.getElementsByTagName("input") 
     If GetElem.ID = "query" Then 'I could just do getElementByID later 
      GetElem.Value = Sheet1.Range("A" & CurRow).Value 
      For Each GetElem2 In Doc.getElementsByTagName("button") 
       If GetElem2.Type = "submit" Then 
        GetElem2.Click 
        Application.Wait (Now + TimeValue("0:00:03")) 
       End If 
      Next GetElem2 
     End If 
     CurRow = CurRow + 1 
    Next GetElem 

End Sub