问题
I am trying to start IE automation using MS Access and I was going through this tutorial.
I understand that IE ReadyState = 4 means that the webpage has loaded
According to the article:
A very common problem people encounter when working with IE in VBA is VBA attempting to run code before Internet Explorer has fully loaded. By using this code, you tell VBA to repeat a loop until IE is ready (IE.ReadyState – 4).
'IE ReadyState = 4 signifies the webpage has loaded (the first loop is set to avoid inadvertently skipping over the second loop)
Do While IE.ReadyState = 4: DoEvents: Loop 'Do While
Do Until IE.ReadyState = 4: DoEvents: Loop 'Do Until
I do not understand the importance of do While loop. Why not just do until IE ready state is 4?
回答1:
While it's usually not necessary, in some cases running
Do Until IE.ReadyState = 4: DoEvents: Loop 'Do Until
by itself will skip the loop altogether because VBA runs the code before the browser has the chance to update the .ReadyState
property to from Complete to Loading. When this property isn't changed in time then this line is automatically true and the loop is skipped entirely. By waiting for the change to take place first, you can usually prevent this issue.
So the first line essentially waits for the .ReadyState
property to change back to 1 so you do not inadvertently skip the line that really matters, which is the 2nd line that actually waits for your page to load.
Take a look at the top portion of another answer of mine. You should be checking for both the .ReadyState
and the .Busy
properties, not just one or the other.
So your 2nd line should really look like this:
Do Until IE.ReadyState = 4 And Not IE.Busy: DoEvents: Loop
来源:https://stackoverflow.com/questions/58508581/why-does-ie-object-need-to-be-looped-over