VBA to open URL, wait for 5 seconds, then open another URL

7.4k views Asked by At

I have a webpage I want to open (URL is generated out of cell values in Excel), but going to that URL directly requires logging in to open. But if I first open the mainpage of the server, I have automatic login, and then I'm able to open the first URL without the need for user/pass.

So far I have this code, which opens IE with both URLs at the same time, in the same window, but different tabs, exactly as I want it to do, except URL2 requires the login. To get around the login, I would like to add a pause between the navigate and navigate2, so the first page can complete loading before the second URL opens.

Can anyone help me with this?

Edit: I have tried the suggestions from below, but it still needs the login. I have tried another solution, which is not optional, but it works. It consists of two buttons, running different macros, where the first one opens the main page to get the login, and the second one opens the next URL. I have written them as follows:

First one:

Sub login()
 Dim IE As Object

  Const navOpenInNewTab = &H800
 Set IE = CreateObject("InternetExplorer.Application")
  IE.Visible = True
  IE.Navigate "http://www.example.mainpage.com"
End Sub

Second one:

Sub search()
 Dim IE As Object

  Const navOpenInNewTab = &H800
 Set IE = CreateObject("InternetExplorer.Application")
  IE.Visible = True
  IE.Navigate2 "http://www.example.mainpage.com" & Range("w1").Cells.Value & Range("W2").Cells.Value, CLng(navOpenInNewTab)

End Sub

Is it possible to have a third macro running the other two with a delay between them?

Original code:

Sub open_url()
 Dim IE As Object
  Const navOpenInNewTab = &H800
 Set IE = CreateObject("InternetExplorer.Application")
  IE.Visible = True
   IE.Navigate "http://www.example.mainpage.com"
'here I would like to add a pause for 5 seconds
   IE.Navigate2 "http://www.example.mainpage.com" & Range("w1").Cells.Value & Range("W2").Cells.Value, CLng(navOpenInNewTab)
End Sub
2

There are 2 answers

1
Miguel Febres On

Maybe it would be better to wait until the first page is fully loaded:

   IE.Navigate "http://www.example.mainpage.com"
   Do While IE.Busy Or Not IE.readyState = IE_READYSTATE.complete: DoEvents: Loop
   IE.Navigate2 "http://www.example.mainpage.com" & Range("w1").Cells.Value & Range("W2").Cells.Value, CLng(navOpenInNewTab)

Note that the ReadyState enum READYSTATE_COMPLETE has a numerical value of 4. This is what you should use in the case of late binding (always the case in VBScript).

1
Golemic On

Do you mean something like:

Application.Wait(Now + TimeValue("00:00:05"))