Excel VBA多For循环无法正常工作

我似乎陷入了一个奇怪的问题。 我有下面的Excel VBA代码来访问一个网站,并input一个用户ID(从表1中的用户ID列A),并检索用户的名字后,点击提交button,然后继续其余的用户ID。

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 

问题是代码只能工作一次。 它将第一个用户标识input到文本框中并点击提交。 当它循环并尝试input下一个用户ID时,代码会陷入循环。

如果我删除整个第二个For-Next循环,它将起作用(尽pipe它不提交,它会在文本框中input每个用户标识)。

最重要的是,如果我使用F8逐步debugging代码,一切工作正常。 只有在完全运行代码时才会出现问题。:(

 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