Search code examples
excelvbaselenium-webdriveruserform

How to embed a web page inside a VBA userform with Selenium?


I have a userfrom inside of which a VBA WebBrowser was inserted. I have working code that calls this browser, but is throwing errors because, I think, of the deprecated IE.

I have installed Selenium Basic and webdriver.exe. I can open Edge, but when opened its not inside the user form, let alone anywhere in a worksheet. Any pointers would be appreciated. Here is what I have:

From a cmdbutton on a worksheet Macro "ShowBrowser" is called.

Sub ShowBrowser()
   'Show the form.
    WebBrowser.Show vbModeless
End Sub

The form is named WebBrowser. From Design Mode, the Microsoft Web Browser is inserted. On the properties window, it is renamed to ObjWebBrowser.

From the Project Explorer, I open the form, click View Code, I have this:

Private Sub ObjWebBrowser_Initialize()
     Dim selenium_Obj As New Selenium.EdgeDriver
     Call selenium_Obj.Start("edge", "https://google.com")
    selenium_Obj.Wait 5000
End Sub

I have tried multiple approaches, but cannot find a way to open Edge inside the userform.


Solution

  • The reason why it's relatively simple to embed IE inside a form is indeed due to the control that is provided in the Microsoft Internet Controls Library (ieframe.dll). (More details here)

    enter image description here

    Fig1: Library location

    enter image description here

    Fig2: Control location

    To do the same with Edge, you'd need a similar library that provides that control, but SeleniumBasic does not provide a userform control for that, it (only) provides an API to interact with a running instance of the web browser. This means that it needs to open the application in a separate window.

    Hence, Selenium is not the tool that will allow you to embed a modern web browser inside a VBA userform.

    In order to embed one inside a form, you'd need to make your own control which is no small task especially since Edge isn't based on the ActiveX technology that made most of what is done with IE possible.

    Instead, Edge uses WebView2 and as discussed in another question, no one as yet created a fully fonctional library to bridge the gap between WebView2 and ActiveX. Sam Sirry's comment mentions that there was work done regarding this. You can have a look at the original VBForums post about it or a more recent post, if that's an option you want to look into. Note that I haven't tested those options.

    Nonetheless, if I were you, I would reconsider the need to embed the browser inside the form and try to figure out if showing the browser as a separate window is acceptable or otherwise if it's possible to capture the inputs needed from the user inside the userform and then send those input via HTTP to an API or via selenium running a browser in the background.