Vba excel webbrowser control

Содержание

  1. How to use the WebBrowser control in Visual Basic to open an Office document
  2. Summary
  3. More Information
  4. Creating a Visual Basic application that opens Office documents
  5. Method 1
  6. Method 2
  7. Considerations when you use the WebBrowser control
  8. Considerations when you use the WebBrowser control together with a 2007 Microsoft Office program
  9. References
  10. Programming
  11. Saturday, April 4, 2009
  12. Webbrowser Control in VBA Excel / Word
  13. Использование элемента управления WebBrowser в Visual Basic для открытия документа Office
  14. Аннотация
  15. Дополнительная информация
  16. Создание приложения Visual Basic, которое открывает документы Office
  17. Способ 1
  18. Способ 2
  19. Рекомендации по использованию элемента управления WebBrowser
  20. Рекомендации по использованию элемента управления WebBrowser вместе с программой Microsoft Office 2007
  21. Ссылки

How to use the WebBrowser control in Visual Basic to open an Office document

For a Microsoft Visual C# 2005 and Microsoft Visual C# .NET version of this article, see 304662.

Summary

You may want to display, or embed, a Microsoft Office document directly on a Microsoft Visual Basic form. Microsoft Visual Basic 2005 and Visual Basic .NET do not provide an OLE control that lets you embed an Office document in a form. If you want to embed an existing document and open it as an in-place ActiveX document object within a Visual Basic form, a potential solution for you is to use the WebBrowser control.

This article demonstrates how to browse to an existing Office document and display it in a Visual Basic form by using the WebBrowser control.

More Information

ActiveX documents are embeddable OLE objects that behave more like ActiveX controls than traditional OLE objects. Unlike a traditional embedded object, an ActiveX document is not designed to be a contained object in a larger document. Instead, it is considered in itself a complete document that is merely being viewed (such as with Microsoft Internet Explorer) or collected in a single resource with other documents (such as a Microsoft Office Binder file). An ActiveX document that is hosted in the WebBrowser control is always active; therefore, unlike traditional OLE embedded objects, there is no sense of in-place activation.

While Microsoft Visual Basic .NET and Visual Basic 2005 do not currently support hosting ActiveX documents directly, you may use the WebBrowser control for this purpose. The WebBrowser control (Shdocvw.dll) is a part of Internet Explorer and can only be used on systems that have Internet Explorer installed.

Creating a Visual Basic application that opens Office documents

When you use two methods above to create a Visual Basic application that opens Office documents, you must change the code in Visual Studio 2005. By default, Visual Basic adds one form to the project when you create a Windows Forms project. The form is named Form1. The two files that represent the form are named Form1.vb and Form1.designer.vb. You write the code in Form1.vb. The Form1.designer.vb file is where the Windows Forms Designer writes the code that implements all the actions that you performed by dragging and dropping controls from the Toolbox.

After the Visual Basic application is created, Press F5 to run the project. When you click Browse, the Open dialog box appears and allows you to browse to a Word, Excel, or PowerPoint file. Select any file and click Open. The document opens inside the WebBrowser control, and a message box that displays the name of the Office document server appears

Method 1

In Microsoft Visual Studio 2005 or in Microsoft Visual Studio .NET, create a Windows Application project by using Visual Basic 2005 or Visual Basic .NET. Form1 is created by default.

On the Tools menu, click Customize ToolBox to open the Customize ToolBox dialog box. On the COM Components tab, add a reference to the Microsoft WebBrowser. Click OK to add the WebBrowser control to the Windows Forms toolbox. The WebBrowser control appears with the text Explorer in the toolbox.

Note In Visual Studio 2005, you do not have to do step 2.

Using the Toolbox, add a WebBrowser control, an OpenFileDialog control, and a Button control to Form1. This step adds the AxWebBrowser1 member variable, the OpenFileDialog1 member variable, and the Button1 member variable to the Form1 class.

Define a private member in the Form1 class as follows.

Paste the following code in the Form1 class.

Method 2

In Microsoft Visual Studio 2005 or in Microsoft Visual Studio .NET, create a Windows Application project by using Visual Basic 2005 or Visual Basic .NET. Form1 is created by default.

From the Project menu, select Components to open the Components dialog box. In the Components dialog box, add references to the Microsoft Common Dialog Control and the Microsoft Internet Controls. Click OK to add the items to the toolbox.

Add an instance of the WebBrowser control, CommonDialog control, and a CommandButton to Form1.

Next, add the following code into the Code window for Form1:

Considerations when you use the WebBrowser control

You should consider the following when you use the WebBrowser control:

The WebBrowser control browses to documents asynchronously. When you call WebBrowser1.Navigate, the call returns control to your Visual Basic application before the document has been completely loaded. If you plan to Automate the contained document, you need to use the NavigateComplete2 event to be notified when the document has finished loading. Use the Document property of the WebBrowser object that is passed in to get a reference to the Office document object, which, in the preceding code, is set to oDocument.

The WebBrowser control does not support menu merging.

The WebBrowser control generally hides any docked toolbars before displaying an Office document. You can use Automation to show a floating toolbar using code such as the following.

Newer versions of Internet Explorer (5.0 and later) also allow you to display docked toolbars using the following code.

There are several known issues with having more than one WebBrowser control in a project and having each control loaded with the same type of Office document (that is, all Word documents, or all Excel spreadsheets). It is recommended that you only use one control per project, and browse to one document at a time.

The most common problem is with Office command bars, which appear disabled. If you have two WebBrowser controls on the same form, both of which are loaded with Word documents, and you have displayed toolbars by using one of the preceding techniques, only one set of toolbars is active and works correctly. The other is disabled and cannot be used.

To clear the WebBrowser of its current contents, in the Click event of another command button (or in some other appropriate place in your code), browse to the default blank page by using the following code:

Considerations when you use the WebBrowser control together with a 2007 Microsoft Office program

By default, the 2007 Office programs do not open Office documents in the Web browser. This behavior also affects the WebBrowser control. We recommended that you use a custom ActiveX document container instead of the WebBrowser control when you develop applications that open 2007 Office documents.

For existing applications that require backward compatibility with the WebBrowser control, you can modify the registry to configure Internet Explorer. You can use this method to configure Internet Explorer to open 2007 Office documents in the Web browser. For more information, click the following article number to view the article in the Microsoft Knowledge Base:

927009 A new window opens when you try to view a 2007 Microsoft Office program document in Windows Internet Explorer 7

Note If you modify the registry by using the method that is mentioned in Knowledge Base article 927009, the changes affect the WebBrowser control that you use in the application. The changes also affect all instances of Internet Explorer. Additionally, this method may not work for any future versions of the Microsoft Office suites. Therefore, we recommend that you use this method only for compatibility with a existing application.

References

For more information about how to use the WebBrowser control, click the following article numbers to view the articles in the Microsoft Knowledge Base:

304562 Visual Studio 2005 and Visual Studio .NET do not provide an OLE container control for Windows Forms

927009 A new window opens when you try to view a 2007 Microsoft Office program document in Windows Internet Explorer 7

Источник

Programming

Visual Basic, VBA and MQ4 code snippets and lessons learned.

Saturday, April 4, 2009

Webbrowser Control in VBA Excel / Word

Using the Webbrowser control is a helpful tool in many programming situations. One of the most common tasks that can be automated is interaction with websites. In the following example, I will setup the webbrowser control within the document itself, navigate to a website and send post data along to that site. I’ve changed the site location and the post data fields so the code will not function correctly until you enter that information in.

FYI: it is easy to find out the URL and the post data of the form you want to submit by following these steps:
Open your internet browser and view the site where the data would be entered. View the source code. You will find an HTML tag that says «form action=xxxxxx». The URL we want will be the «xxxxx» portion in that line. Then you will want to note all of the input tag name values within that form. These will look like «input type=xxx name=xxx». When posting your data (or when using a GET command, for that matter) you will need to know the input names so you can send the relevant data along with them.
In the example below i’ve included inputs named «fname», «lname», and «zip» which you will see in the postdata variable. The script below also reads through a list of 10 rows in an excel spreadsheet. If column «A» has data in it, then it pulls data from Columns A, B, and C corresponding to our variables «fname», «lname», and «zip», in that order. Then it moves on to the next row and loops until there is no more data or until row 10 is reached.

Источник

Использование элемента управления WebBrowser в Visual Basic для открытия документа Office

Сведения о версии Microsoft Visual C# 2005 и Microsoft Visual C# .NET в этой статье см. в 304662.

Аннотация

Может потребоваться отобразить или внедрить документ Microsoft Office непосредственно в форме Microsoft Visual Basic. Microsoft Visual Basic 2005 и Visual Basic .NET не предоставляют элемент управления OLE, позволяющий внедрять документ Office в форму. Если вы хотите внедрить существующий документ и открыть его как объект документа ActiveX на месте в форме Visual Basic, можно использовать элемент управления WebBrowser.

В этой статье показано, как перейти к существующему документу Office и отобразить его в форме Visual Basic с помощью элемента управления WebBrowser.

Дополнительная информация

Документы ActiveX — это встраиваемые объекты OLE, которые ведут себя больше как элементы ActiveX, чем традиционные объекты OLE. В отличие от традиционного внедренного объекта, документ ActiveX не является автономным объектом в более крупном документе. Вместо этого он сам по себе считается полным документом, который просто просматривается (например, в Microsoft Internet Explorer) или собирается в одном ресурсе с другими документами (например, файлом Привязки Microsoft Office). Документ ActiveX, размещенный в элементе управления WebBrowser, всегда активен; Поэтому, в отличие от традиционных внедренных объектов OLE, нет смысла активации на месте.

Хотя Microsoft Visual Basic .NET и Visual Basic 2005 в настоящее время не поддерживают размещение документов ActiveX напрямую, для этой цели можно использовать элемент управления WebBrowser. Элемент управления WebBrowser (Shdocvw.dll) является частью Internet Explorer и может использоваться только в системах, на которых установлен Internet Explorer.

Создание приложения Visual Basic, которое открывает документы Office

При использовании двух описанных выше методов для создания приложения Visual Basic, которое открывает документы Office, необходимо изменить код в Visual Studio 2005. По умолчанию Visual Basic добавляет одну форму в проект при создании Windows Forms проекта. Форма называется Form1. Два файла, представляющих форму, имеют имена Form1.vb и Form1.designer.vb. Вы пишете код в Form1.vb. В файле Form1.designer.vb конструктор Windows Forms код, реализующий все выполняемые действия путем перетаскивания элементов управления с панели элементов.

После создания приложения Visual Basic нажмите клавишу F5, чтобы запустить проект. При нажатии кнопки «Обзор» откроется диалоговое окно «Открыть», в которое можно перейти к файлу Word, Excel или PowerPoint. Выберите любой файл и нажмите кнопку » Открыть». Документ откроется в элементе управления WebBrowser, и появится окно сообщения с именем сервера документов Office.

Способ 1

В Microsoft Visual Studio 2005 или Microsoft Visual Studio .NET создайте проект приложения Windows с помощью Visual Basic 2005 или Visual Basic .NET. Form1 создается по умолчанию.

В меню «Сервис » щелкните «Настроить панель элементов», чтобы открыть диалоговое окно «Настройка панели элементов». На вкладке COM Components (Компоненты COM) добавьте ссылку на Microsoft WebBrowser. Нажмите кнопку «ОК», чтобы добавить элемент управления WebBrowser на Windows Forms элементов. Элемент управления WebBrowser отображается с обозревателем текста на панели элементов.

Примечание В Visual Studio 2005 не нужно делать шаг 2.

С помощью панели элементов добавьте элемент управления WebBrowser, элемент Управления OpenFileDialog и элемент управления Button в Form1. Этот шаг добавляет переменную-член AxWebBrowser1, переменную-член OpenFileDialog1 и переменную-член Button1 в класс Form1.

Определите закрытый член в классе Form1 следующим образом.

Вставьте следующий код в класс Form1.

Способ 2

В Microsoft Visual Studio 2005 или Microsoft Visual Studio .NET создайте проект приложения Windows с помощью Visual Basic 2005 или Visual Basic .NET. Form1 создается по умолчанию.

В меню «Проект» выберите «Компоненты», чтобы открыть диалоговое окно «Компоненты». В диалоговом окне «Компоненты» добавьте ссылки на элемент управления «Общий диалог» (Майкрософт) и «Элементы управления Интернетом (Майкрософт)». Нажмите кнопку «ОК», чтобы добавить элементы на панель элементов.

Добавьте экземпляр элемента управления WebBrowser, элемента управления CommonDialog и commandButton в Form1.

Затем добавьте следующий код в окно кода для Form1:

Рекомендации по использованию элемента управления WebBrowser

При использовании элемента управления WebBrowser следует учитывать следующее:

Элемент управления WebBrowser асинхронно просматривает документы. При вызове WebBrowser1.Navigate вызов возвращает элемент управления приложению Visual Basic до полной загрузки документа. Если вы планируете автоматизировать автономный документ, необходимо использовать событие NavigateComplete2, чтобы получать уведомления о завершении загрузки документа. Используйте свойство Document объекта WebBrowser, передаваемого для получения ссылки на объект документа Office, который в приведенном выше коде имеет значение oDocument.

Элемент управления WebBrowser не поддерживает слияние меню.

Элемент управления WebBrowser обычно скрывает закрепленные панели инструментов перед отображением документа Office. Вы можете использовать службу автоматизации для отображения плавающей панели инструментов с помощью следующего кода.

Более новые версии Internet Explorer (5.0 и более поздние версии) также позволяют отображать закрепленные панели инструментов, используя следующий код.

Существует несколько известных проблем с наличием нескольких элементов управления WebBrowser в проекте и загрузкой каждого элемента управления с одним типом документа Office (т. е. всех документов Word или всех электронных таблиц Excel). Рекомендуется использовать только один элемент управления для каждого проекта и перейти к одному документу за раз.

Наиболее распространенная проблема связана с панели команд Office, которые отображаются отключенными. Если у вас есть два элемента управления WebBrowser в одной форме, оба из которых загружены с документами Word, и вы отображали панели инструментов с помощью одного из описанных выше методов, активен и работает только один набор панелей инструментов. Другая функция отключена и не может использоваться.

Чтобы очистить webBrowser от текущего содержимого, в событии Click другой кнопки команды (или в другом месте в коде) перейдите на пустую страницу по умолчанию, используя следующий код:

Рекомендации по использованию элемента управления WebBrowser вместе с программой Microsoft Office 2007

По умолчанию программы Office 2007 не открывают документы Office в веб-браузере. Это поведение также влияет на элемент управления WebBrowser. Мы рекомендуем использовать пользовательский контейнер документов ActiveX вместо элемента управления WebBrowser при разработке приложений, которые открывают документы Office 2007.

Для существующих приложений, для которых требуется обратная совместимость с элементом управления WebBrowser, можно изменить реестр, чтобы настроить Internet Explorer. Этот метод можно использовать для настройки Internet Explorer для открытия документов Office 2007 в веб-браузере. Для получения дополнительных сведений щелкните номер следующей статьи, чтобы просмотреть статью в базе знаний Майкрософт:

927009 откроется новое окно при попытке просмотреть документ программы Microsoft Office 2007 в Windows Internet Explorer 7

Примечание При изменении реестра с помощью метода, упомянутого в статье базы знаний 927009, изменения влияют на элемент управления WebBrowser, используемый в приложении. Изменения также влияют на все экземпляры Internet Explorer. Кроме того, этот метод может не работать для будущих версий наборов Microsoft Office. Поэтому мы рекомендуем использовать этот метод только для обеспечения совместимости с существующим приложением.

Ссылки

Дополнительные сведения об использовании элемента управления WebBrowser см. в следующих номерах статей, чтобы просмотреть статьи в базе знаний Майкрософт:

304562 Visual Studio 2005 и Visual Studio .NET не предоставляют элемент управления контейнером OLE для Windows Forms

927009 откроется новое окно при попытке просмотреть документ программы Microsoft Office 2007 в Windows Internet Explorer 7

Источник

Using the Webbrowser control is a helpful tool in many programming situations. One of the most common tasks that can be automated is interaction with websites. In the following example, I will setup the webbrowser control within the document itself, navigate to a website and send post data along to that site. I’ve changed the site location and the post data fields so the code will not function correctly until you enter that information in.

FYI: it is easy to find out the URL and the post data of the form you want to submit by following these steps:
Open your internet browser and view the site where the data would be entered. View the source code. You will find an HTML tag that says «form action=xxxxxx». The URL we want will be the «xxxxx» portion in that line. Then you will want to note all of the input tag name values within that form. These will look like «input type=xxx name=xxx». When posting your data (or when using a GET command, for that matter) you will need to know the input names so you can send the relevant data along with them.
In the example below i’ve included inputs named «fname», «lname», and «zip» which you will see in the postdata variable. The script below also reads through a list of 10 rows in an excel spreadsheet. If column «A» has data in it, then it pulls data from Columns A, B, and C corresponding to our variables «fname», «lname», and «zip», in that order. Then it moves on to the next row and loops until there is no more data or until row 10 is reached.



Sub getpage()
Dim URL As String, PostData() As Byte, kp as integer
URL = "https://examplepage.com/script.cgi"
For kp = 1 To 10
'iterate through the first ten rows
If Not Me.Cells(kp, 1) = "" Then
'if cell A1 isn't empty then proceed
PostData = "fname=" & Me.Cells(kp, 1) & "&lname=" _
& Me.Cells(kp, 2) & "&zip=" & Me.Cells(kp, 3)
'set our postdata string to the variables and their
'corresponding values
PostData = StrConv(PostData, vbFromUnicode)
'convert the string
Me.WebBrowser1.Silent = True
'stop the browser from alerting us of anything
Me.WebBrowser1.Navigate URL, 0, "", PostData, ""
'tell the browser to goto the URL
Do
DoEvents
Loop Until Me.WebBrowser1.ReadyState = READYSTATE_COMPLETE
'let this loop run until the webbrowser has finished
'loading the page
End If
Next kp
End Sub

As you will see, the code can iterate through a list of items and run a request to a website, filling in the data the user desires and retrieving the results. the me.webbrowser1.silent = true code stops the browser from spitting any messageboxes back at us so we can be sure there are no problems automating the process. The line «loop until me.webbrowser1.readystate = readystate_complete» is a line that waits until the webbrowser control has responded that it has fully finished loading the page. the words readystate_complete can be replaced by the number 4, as they are interchangeable. However, I have found that this code is often flawed as the webbrowser does not always return a reliable result about whether it has finished loading (it often says it’s done loading but has not loaded the innerhtml property yet). I will deal with this issue in a later post.

For now, this should be a sufficient example to get you POSTing data using the webbrowser control. A GET command would be even simpler. You just append the data that is in the post variable to the end of the web address, with a question mark separating the web address and the postdata (ie. http://testsite.com/script.cgi?variable1=value&variable2=2ndvalue&variable3=thirdvalue)
Note, when combining the variables in the string you separate each new variable with the «&» character and place the input name on the left of the equals sign and the value on the right of it.

I have been assigned the task of automating a web based task ( for a HTTPS website). The users currently are filling in the Excel sheet with the data, they now want to automate excel in such a way that it directly controls the browser and fills in the data.

I found the iMacros Scripting edition as a possible solution for doing this, I wanted to know if there are any other similar tools which can be used for controlling the browser and filling in data.

I also had a look at the Selenium Client Driver, but I am not sure on how to use it in Excel VBA.

Any help would be appreciated.

Thanks,

Community's user avatar

asked Sep 20, 2011 at 17:44

Darshan Bhatia's user avatar

5

You can use Selenium from Visual Basic Editor by installing the tools provided here :

http://code.google.com/p/selenium-vba/

There is a Selenium IDE plugin to automatically record a script in VBA and an installation package to run Selenium command in Visual Basic Editor.

The following example starts firefox, opens links in the 1st column, compares the title with the 2nd column and past the result in the 3rd column.
Used data are in a sheet, in a range named «MyValues».

Public Sub TC002()
   Dim selenium As New SeleniumWrapper.WebDriver, r As Range
   selenium.Start "firefox", "http://www.google.com" 
   For Each r In Range("MyValues").Rows
     selenium.open r.Cells(, 1)
     selenium.waitForNotTitle ""
     r.Cells(, 3) = selenium.verifyTitle(r.Cells(, 2))
   Next
   selenium.stop
End Sub

answered Mar 6, 2012 at 18:31

florentbr's user avatar

This sample open stackoverflow site an show IE

Sub OpenIE()
'officevb.com
Dim ie As Object
Set ie = CreateObject("InternetExplorer.Application")

ie.Navigate "http://www.stackowerflow.com"

 'wait load
 While ie.ReadyState <> READYSTATE_COMPLETE
  DoEvents
 Wend

ie.Visible = True

End Sub

[]’s

answered Sep 21, 2011 at 0:54

Bruno Leite's user avatar

Bruno LeiteBruno Leite

1,40312 silver badges17 bronze badges

0

I use this code for reading data from excel and passin it to selenium for to do task like «click, select, close etc» and also you can write data to excel.

This is in python i don know VB and i do know perl if u wish i’ll give same code in perl too.

i hop this may help.

from xlwt import Workbook

import xlrd

testconfigfilename="testconfig.xls"

    if (len(sys.argv) > 1):

        testconfigfilename=sys.argv[1]       

    wb = xlrd.open_workbook(testconfigfilename);

    wb.sheet_names();

    sh = wb.sheet_by_index(0); 'Sheet 0 - selenium server configuration'



    seleniumHost = sh.cell(1,0).value

    seleniumPort = int(sh.cell(1,1).value)

    testBaseURL = sh.cell(1,2).value

    browser = sh.cell(1,3).value

    timeout = int(sh.cell(1,4).value)

    path = sh.cell(1,5).value

outputwb = Workbook()

    outputsheet = outputwb.add_sheet("result",cell_overwrite_ok=True) #get the first sheet in the result xls 

outputsheet.write(RowNumber,colNumber,"data")

answered Oct 10, 2011 at 6:52

Sirga's user avatar

SirgaSirga

2461 gold badge4 silver badges13 bronze badges

Web Browser In The Spreadsheet


Introduction


While I was hanging around the net, I found an easy way to have a copy of internet explorer in a spreadsheet. Why this might be useful? Well, since the explorer will be incorporated in the spreadsheet, you will not have to open a separate (external) instance of internet explorer. So, in cases you want to copy some data from a web page, you will avoid the disturbing switching between excel and internet explorer. Furthermore, since the explorer will be incorporated in a modeless form you will be able to continue your excel work normally.


How to do it


Step 1: In the VBA editor (ALT + F11), create a userform as usual: Right click at any of the objects and then insert -> UserForm.

Web Browser 1

Step 2: In order to add the Webbrowser object you should do the following: Right click on the toolbox and select Additional Controls.

Web Browser 2

Next, from the available choices, select Microsoft Web Browser and then click OK.

Web Browser 3

Step 3: Add controls to your userform and format it according to your needs and taste.

Web Browser 4

Step 4: Finally, use the code below in order to make your browser functional.


VBA code


Option Explicit

    '-------------------------------------------------------------------
    'This is the code for handling the various buttons in web browser.

        'Written by:    Christos Samaras
    'Date:          03/05/2012
    'e-mail:        [email protected]
    'site:          https://myengineeringworld.net/////
    '-------------------------------------------------------------------

Private Sub btnGo_Click()

            'Handles the Go button.
    Me.objWebBrowser.Navigate2 Me.txtURL.Value

    End Sub

Private Sub btnForward_Click()

    'Handles the Forward button.
    On Error Resume Next
    Me.objWebBrowser.GoForward

    End Sub

Private Sub btnBackward_Click()

    'Handles the Backward button.
    On Error Resume Next
    Me.objWebBrowser.GoBack

    End Sub

Private Sub btnHome_Click()

    'Handles the Home button.
    On Error Resume Next
    Me.objWebBrowser.GoHome

End Sub

Private Sub btnExit_Click()

    'Handles the Exit button.
    Me.Hide

End Sub

Private Sub UserForm_Initialize()

    'Aligns the userform at the top left corner.
    Me.StartUpPosition = 0
    Me.Top = 0
    Me.Left = 0

         'Setting the initial page of browser.
    Me.objWebBrowser.Navigate2 "https://myengineeringworld.net//////"

End Sub

Following the procedure that was described above, I created a workbook that contains a modeless form with a webbrowser object. Try yourself and create your “own version” of internet explorer inside Excel.


Update 22/10/2013


Update

What I really like in this blog is the conversation with other people through comments., since I have the opportunity to learn new things. Yesterday for example Mike pointed out that the web browser control doesn’t work anymore with Google Maps page. He also suggested a solution, which I would like to add in case someone has the same issue.

Problem: the web browser control uses the Internet Explorer (IE) 6 settings. It seems that Google Maps stopped supporting that version, so if someone tries to open Google Maps the page looks like frozen.  

Solution: it requires a small change in registry. Below there are instructions for Windows 7, although similar steps can be used in other Windows versions:

1. Press the Start button, in the search box write regedit and press enter.

2. If you have 32-bit Office go to HKEY_LOCAL_MACHINESoftwareMicrosoftInternet ExplorerMainFeatureControlFEATURE_BROWSER_EMULATION. For 64-bit Office the location is slightly different: HKEY_LOCAL_MACHINESOFTWAREWow6432NodeMicrosoftInternet ExplorerMAINFeatureControlFEATURE_BROWSER_EMULATION.

3. Add a new DWORD (32-bit) Value in the folder (using the right mouse click) and name it Excel.exe.

Registry Edit - Web Browser Control

4. Double click to Excel.exe and in the edit window select a Decimal Base (using the radio button).

5. According to your Internet Explorer version that you have installed at your computer fill one of the following values:

  • 7000 – Internet Explorer 7
  • 8000 – Internet Explorer 8
  • 9000 – Internet Explorer 9
  • 10000 – Internet Explorer 10

Web Browser Control - New Registry Value

More info about these values can be found at Microsoft’s site. If you have followed the previous steps successfully you will be able to run Google Maps from the sample file.

Google Maps In Web Browser Control

I would like to thanks once again Mike for his contribution.


Download it from here


Download

This file can be opened with Excel 2007 or newer. Please, remember to enable macros before using this workbook.

Page last modified: January 6, 2019

Author Image

Hi, I am Christos, a Mechanical Engineer by profession (Ph.D.) and a Software Developer by obsession (10+ years of experience)! I founded this site back in 2011 intending to provide solutions to various engineering and programming problems.

Add Content Block

Web browser in User form

In this article you will learn how to use a web browser in the user form. You can search anything or open a website using the text box.

Web Browser in User form

Web Browser in User form

Below are the steps to create the web browser in the user form-

  • Go to the Visual basic editor (Press Alt+F11)
  • Open the Toolbox.

Open the Toolbox

Open the Toolbox
  • Right Click on the Tool box and click on Additional Controls.

Additional Controls Option

Additional Controls Option
  • Select the Microsoft Web Browser in Additional Controls window.

Additional Controls window

Additional Controls window
  • Web Browser control will be added in the Tool box

Web Browser control

Web Browser control
  • Drag the Web browser on the user form.
  • Create a Text box to search or typing the URL
  • Create a Command Button to search.

User form

User form
  • Double Click on the command button and put the below given code-
Private Sub CommandButton1_Click()

    Me.WebBrowser1.Navigate Me.TextBox1.Value

End Sub

Coding

Coding

Click here to download this Excel workbook.

Watch the step by step video tutorial:

Meet PK, the founder of PK-AnExcelExpert.com! With over 15 years of experience in Data Visualization, Excel Automation, and dashboard creation. PK is a Microsoft Certified Professional who has a passion for all things in Excel. PK loves to explore new and innovative ways to use Excel and is always eager to share his knowledge with others. With an eye for detail and a commitment to excellence, PK has become a go-to expert in the world of Excel. Whether you’re looking to create stunning visualizations or streamline your workflow with automation, PK has the skills and expertise to help you succeed. Join the many satisfied clients who have benefited from PK’s services and see how he can take your Excel skills to the next level!

Advanced Excel and VBA tutorials

Понравилась статья? Поделить с друзьями:
  • Vba excel автоматический запуск макроса
  • Vba excel vlookup пример
  • Vba excel type mismatch error 13 что
  • Vba excel автозапуск макроса
  • Vba excel vba tutorial