WebBrowser on MultiPage failing with a 'Navigate' of object 'IWebBrowser2' error when the tabs are changed

270 Views Asked by At

On Page 4 of the MultiPage form I've created a WebBrowser1 object. On Page 4 there are 2 buttons: one for msn.com, the other for google.com. If the UserForm defaults to Page 4 when opened, the buttons work fine initially, but if one of the other Pages is selected, and then the user returns to Page 4, clicking either one of the buttons causes the macro to crash with an error message 'Navigate' of object 'IWebBrowser2' failed.

   Private Sub CommandButton23_Click()
      Me.WebBrowser1.Navigate ("https://www.msn.com")
   End Sub

   Private Sub CommandButton24_Click()
      Me.WebBrowser1.Navigate ("https://google.com")
   End Sub
1

There are 1 best solutions below

0
Michael Riley On

It appears that the WebBrowser needs to be "refreshed" each time Page 4 gets re/loaded. One solution is to eliminate the WebBrowser1 object from the UserForm and dynamically created a WebBrowser (wbr, below) initially, and then each time Page 4 is reselected.

Dim wbr As SHDocVw.WebBrowser

Private Sub MultiPage1_Change()
    If MultiPage1.SelectedItem.Name = "Page 4" Then
        Set wbr = Nothing
        Set wbr = Me.MultiPage1.SelectedItem.Controls.Add("Shell.Explorer.2")

        wbr.Height = 700
        wbr.Left = 96
        wbr.Top = 24
        wbr.Width = 570
        wbr.Navigate "About:Blank"
    End If
End Sub

Private Sub UserForm_Initialize()
    Set wbr = Me.MultiPage1.SelectedItem.Controls.Add("Shell.Explorer.2")

    wbr.Height = 700
    wbr.Left = 96
    wbr.Top = 24
    wbr.Width = 570
    wbr.Navigate "About:Blank"
End Sub

I can't take credit for this solution - it was actually on another post in stackoverflow for a different problem!

Check it out: Resizing WebBrowser Control on Excel UserForm with DPI