繁体   English   中英

Excel VBA多个For循环不起作用

[英]Excel VBA multiple For loop not working

我似乎陷入了一个奇怪的问题。 我有下面的Excel VBA代码访问网站并输入一个userID(来自表1中的userID列A)并检索用户的名称,该用户在按下提交按钮后显示,然后继续使用其余的userID。

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 

问题是代码只能运行一次。 它将第一个userID输入文本框并点击Submit。 当它循环并尝试输入下一个userID时,代码卡在一个循环中。

如果我删除整个第二个For-Next循环它可以工作(虽然它没有提交,它会输入文本框中的每个userID)。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM