问题
I am automating IE through VBA and I can't seem to get the VBA code to wait until the page is loaded before grabbing the document. This is leading to all sorts of failures with my code being too fast. How can I get VBA to wait for the IE page to load? Many of the methods I have tried I have found on stackoverflow but none seem to work for me.
ie
is my InternetExplorer
object.
I have tried, to no avail:
Do
If ie.readyState = 4 Then
Exit Do
Else
DoEvents
End If
Loop
Also:
Do While ie.Busy Or Not ie.ReadyState = READYSTATE_COMPLETE
DoEvents
Loop
Also:
Do
DoEvents
Loop Until ie.ReadyState = READYSTATE_COMPLETE
I even tried:
Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
...
Do
Sleep 250
Loop Until ie.readyState = READYSTATE_COMPLETE
None of these have worked, the code skips over the loop immediately and tries to grab the html document of the page even though the page has not finished loading.
I am navigating to a login page, filling in a username and password, and clicking log-in. After I log-in I need to change some fields (drop downs and text boxes). After I change these fields I use VBA to click a button to save the settings and then navigate to another page. The code does not properly set the fields because it skips past waiting for the page to load, thus I enter the next part of my code with incorrect settings.
I am wondering if this is possibly due to an ajax request? I don't know how to even tell.
Does anyone have a reliable means of waiting for a page to load in IE before grabbing the html document?
I know the code is doing what I want because if I manually step through it and wait for the page to load, it behaves as expected.
I can add more clarification if necessary.
回答1:
You could wait for the DocumentComplete event to fire. But for that you need to have the browser control placed on a worksheet. In the code of that worksheet, enter this code (assuming you named the browser control ie
):
Private docComplete As Boolean
Private Sub ie_DocumentComplete(ByVal pDisp As Object, url As Variant)
docComplete = True
End Sub
Public Sub NavigateAndWait(url As String)
docComplete = False
ie.Navigate url
Do
DoEvents
Loop Until docComplete
End Sub
Sub Main()
' Example use
NavigateAndWait "www.google.com"
MsgBox "Ready"
End Sub
By making NavigateAndWait
a Public Sub
you can call it from other modules you might have. It is best to move code that needs ie
into this sheet's module. Note that the browser control must be visible and on the active sheet for the DocumentComplete event to fire.
回答2:
Sorry I don't have enough rep so I have to add an answer but did you try 1000 or 2000 (1 or 2 seconds) in your 3rd option? Depending on what IE is doing it may take more than 250 milliseconds to load.
来源:https://stackoverflow.com/questions/33353565/how-do-i-make-vba-wait-for-ie-page-to-load