How do I embed a browser in an Excel VBA form?

和自甴很熟 提交于 2019-12-23 05:11:35

问题


In the past I have used the Microsoft WebBrowser control in many VB6 and Excel VBA forms. I need to do it again, but I can't figure out how to do it.

I tried opening an old VB6 project and I got this error message:

Line 17: Class SHDocVwCtl.WebBrowser of control WebBrowser was not a loaded control class.

I tried adding a reference to Microsoft Web Browser to a new VBA project, but it doesn't exist.

I tried adding a reference to msi.dll as suggested here, but didn't help.

I tried from the Developer ribbon - Insert - More Controls - Microsoft Web Browser, it does exist, but it says Cannot insert object.

I tried using the Shell.Explorer.2 object as described here, but I get an error:

Sheet1.OLEObjects.Add ClassType:="Shell.Explorer.2", Left:=147, Top:=60.75, Width:=400, Height:=400

Run-time error '1004': 
Cannot insert object.

The only way that worked was opening an IE window, but I need the browser to be embedded in a form because I need to add a few custom buttons:

Set IE = CreateObject("InternetExplorer.Application") 
IE.Visible = True

回答1:


I was not able to get the good old Web Browser control to appear in the VBA control toolbox as it used to, but I was able to dynamically insert it in a form from the code. So I can't drag the little globe into a form, but that's not a problem.

Some comments mentioned changing a value in the registry. That is required in order to insert an embedded browser inside a worksheet, but has no effect on the form.

It was enough to add a reference to Microsoft Internet Controls (ieframe.dll), then use the following code in a form:

Option Explicit

Private WithEvents WB As WebBrowser

Private Sub UserForm_Activate()
  Set WB = Me.Controls.Add("Shell.Explorer.2")
  WB.Navigate "http://google.com"
End Sub

Private Sub WB_NavigateComplete2(ByVal pDisp As Object, URL As Variant)
  Debug.Print "WB_NavigateComplete2"
End Sub

EDIT

@VictorK in a comment reminded me that I need to right click on the toolbox to add the control. I did remember about the control being added there after adding the reference, but I didn't remember (nor think) to right click and add the control.

So... all I needed to do was to add a reference to ieframe.dll instead of Microsoft Web Browser, just because Microsoft Web Browser doesn't appear in the list. Everything else seems to be working fine.

I still don't know why the old VB6 application doesn't load, but at this point I really don't care.



来源:https://stackoverflow.com/questions/51501213/how-do-i-embed-a-browser-in-an-excel-vba-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!