excel 2016 UserForm vba webBrowser control: how to detect that no web page has been found for a (defective) URL?

I have a webbrowser control working in Excel UserForm.

If I call it with a legitimate url, I get the web page displayed:
Me.WebBrowser1.Navigate "http://bbc.co.uk"

If I use an erroneous url, the control displays a coloured text message that the page for that url has not been found.
I would like some code that tells me that the url was not found, so I can reset the form and ask the user to enter a new URL.

Who is Participating?
ste5anConnect With a Mentor Senior DeveloperCommented:
In simple cases you may use the LocationUrl, it would be different then. But the normal approach is using the NavigateError event.

Bind the web browser control to a private variable WithEvents, then you can hook into that event.
Kelvin4Author Commented:
Kelvin4Author Commented:
UserForm.name = frm_webBrowser1
.Control.name =  webBrowser1

Following @ste5an, I used _NavigateError as follows:

In the code sheet for frm_webBrowser1 I  placed:

Private Sub WebBrowser1_NavigateError(ByVal pDisp As Object, URL As Variant, Frame As Variant, StatusCode As Variant, Cancel As Boolean)
    Dim str As String
    str = "No web page available for url: " & vbCrLf & vbCrLf & URL & vbCrLf & vbCrLf 'WebBrowser1_NavigateError url = " & URL & " statusCode = " & StatusCode
    str = str & "if the url can be corrected NOW: click 'OK', else click '"
    MsgBox str, , "Web Browser: unknown URL"
End Sub

This trapped urls for unrecognised web pages, and allowed urls of actual web pages.
I had no need to bind the web browser control to a private variable WithEvents, probably because the Following event  was already available  in the VBE for WebBrowser1.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.