Веб браузер vba excel

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

Hi I’m trying to dynamically create a web browser inside a spreadsheet and then use it but the WebBrowser functions don’t seem to work

Here is how I create the WebBrowser

Set myWebBrowser = Sheets("test").OLEObjects.Add(ClassType:="Shell.Explorer.2", Link:=False, DisplayAsIcon:=False, left:=147, top:=60.75, width:=141, height:=96)

This will work

myWebBrowser.top = 10

But this will give me an error

myWebBrowser.Navigate ("about:blank")

Any ideas on what should I do thank you

UPDATE:

This will also don’t work and give an error:

myWebBrowser.Object.Document.body.Scroll = "no"
myWebBrowser.Object.Silent = True
myWebBrowser.Object.Navigate ("about:blank")
While myWebBrowser.Object.ReadyState <> READYSTATE_COMPLETE
    Application.Wait (Now + TimeValue("0:00:01"))
Wend
myWebBrowser.Object.Refresh

UPDATE 2 (almost there):

Now I need a way to remove the Sheet2.Activate Sheet1.Activate

Sheet2.Activate
Sheet1.Activate

Set wb = myWebBrowser.Object

With wb
    .Silent = True
    .Navigate "about:blank"
    Do While .ReadyState <> READYSTATE_COMPLETE
        Application.Wait (Now + TimeValue("0:00:01"))
    Loop
    .Document.Open "text/html"
    Do While .ReadyState <> READYSTATE_COMPLETE
        Application.Wait (Now + TimeValue("0:00:01"))
    Loop
    .Document.write html
    .Document.Close
    .Document.body.Scroll = "no"
    .Refresh
    Debug.Print .Document.body.innerHTML
End With

When you really stop to think about it, an Internet browser in its simplest form isn’t really that impressive an application. I mean, yes, the Internet is amazing by anyone’s standards. The concept of linking so many of the world’s computers and mobile devices within this massive network, that is epic. But the concept of transferring a text file with special code in it onto a computer screen is not really a big deal.

When you really stop to think about it, an Internet browser in its simplest form isn’t really that impressive an application. I mean, yes, the Internet is amazing by anyone’s standards. The concept of linking so many of the world’s computers and mobile devices within this massive network, that is epic. But the concept of transferring a text file with special code in it, and displaying that transferred text onto the computer screen — that’s really not a big deal.

In fact, thanks to the embedded references in applications that use VBA, you can input and output webpages via your own applications. If you’ve followed our past scripting articles, then you know we love VB script and VBA, like my article on maximizing windows, Paul’s on self-updating charts, and Saikat’s on sending out mass emails.

Using the approach below, you can use Word, Access or Excel to read HTML documents on the web, alter those documents, and then output whatever you want in a new browser window.

It may sound like something that only an experienced VBA programmer can do, but in this article I’m going to show you how you can do this yourself, starting with a basic procedure to output data from within your own application to a webpage.

Enabling Microsoft Internet Controls

The first step, no matter how you want to make use of the ability to input/output your own HTML via VBA, is to enable the Microsoft Internet Controls reference.

In Excel, you do this by clicking on the «Developer» menu item, clicking Design Mode, and then clicking on the «View Code» button. This may appear different in older versions of Excel, but essentially you need to find where you can launch the VBA code editor.

make your own internet browser

In the VBA editor, click on Tools, and then References.

make an internet browser

In the References window, scroll all the way down until you see «Microsoft Internet Controls«. Check the box and then click «OK«.

make an internet browser

Now, within your VBA code, you will be able to create objects that can get information off the Internet, and you can output your own HTML documents that the user can view in their own browser.

Inputting and Outputting HTML

The first thing that you’ll want to accomplish here is outputting information to HTML. Think about how much you can do once you can output information to a perfectly formatted HTML webpage. You can extract data from your Excel spreadsheets and output them in a nicely formatted report.

make an internet browser

To create this feature, you’ll need to insert a command button on your sheet. Under the Developer menu, click on Design Mode, and then click the «Insert» button. You’ll see a dropdown of controls that you can add to your sheet.

In this case, click the button control and place it in your sheet. Make sure there’s some data in the sheet (or any sheet), that you want to output to a report when the button is clicked. Left click on the button to select it and click «View Code«.

Enter the following code:

Sub Button1_Click()
 Dim objIE As Object
 Dim HTML As String
 '----------The HTML CODE GOES FROM HERE AND DOWN----------
 HTML = "<HTML><TITLE>HTML Report Page</TITLE>" & _
 "<BODY><FONT COLOR = BLUE><FONT SIZE = 5>" & _
 "<B>The Following Are Results From Your Daily Calculation</B>" & _
 "</FONT SIZE><P>" & _
 "Daily Production: " & Sheet1.Cells(1, 1) & "<p>" & _
 "Daily Scrap: " & Sheet1.Cells(1, 2) & "<p></BODY></HTML>"
 '----------The HTML CODE GOES HERE AND ABOVE---------
 On Error GoTo error_handler
 Set objIE = CreateObject("InternetExplorer.Application")
 With objIE
 .Navigate "about:blank"
 Do While .Busy: DoEvents: Loop
 Do While .ReadyState <> 4: DoEvents: Loop
 .Visible = True
 .Document.Write HTML
 End With
 Set objIE = Nothing
 Exit Sub
error_handler:
 MsgBox ("Unexpected Error, I'm quitting.")
 objIE.Quit
 Set objIE = Nothing
End Sub

This code outputs the HTML that you’ve defined in that output string. As you can see from my example above, you can embed data from any sheet in Excel into your HTML string. Here is the resulting webpage report:

make your own internet browser

Now that you have HTML output working, the next step to make your VBA script work virtually like a web browser is to read in HTML from some website, manipulate the data, and then output it into an HTML output page.

Sub Button1_Click()
 Dim objIE As Object
 Dim HTML As String
 On Error GoTo error_handler
 Set objIE = CreateObject("InternetExplorer.Application")
 With objIE
 .Navigate "http://www.google.com"
 Do While .Busy: DoEvents: Loop
 Do While .ReadyState <> 4: DoEvents: Loop
 .Visible = True
 HTML = objIE.Document.Body.innerHTML
 .Document.Write "<html><title>My Own Google Results!</title><body><h1>This is an Edited Version of the Google Page!</h1>" & HTML & "</body></html>"
 End With
 Set objIE = Nothing
Exit Sub
error_handler:
 MsgBox ("Unexpected Error, I'm quitting.")
 objIE.Quit
 Set objIE = Nothing
End Sub

What I’ve done here is used the IE object to read HTML from Google into a text variable in VBA called HTML. I then placed my own HTML output text in the top of the page, and then outputted the same HTML to the VBA HTML output. This is what that looks like:

This is a very basic example of what this is capable of. But if you think about it, once you have the HTML from a webpage loaded into your VBA string variable, you can search for specific lines in the page, look for images, search out email addresses of phone numbers — or you could rewrite the entire input page into a new, edited version of the same page in whatever format you like and with any modifications you like.

Doing this would require a bit of string manipulation prowess — but nothing is impossible once you’ve read in the HTML source from the web.

Do you see any potential for using either HTML input or output in your own applications? Can you think of any cool uses for this script? Share your thoughts in the comments section below.

Image credit: Shutterstock

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

If you want a more robust solution with ShellExecute that will open ANY file, folder or URL using the default OS associated program to do so, here is a function taken from http://access.mvps.org/access/api/api0018.htm:

'************ Code Start **********
' This code was originally written by Dev Ashish.
' It is not to be altered or distributed,
' except as part of an application.
' You are free to use it in any application,
' provided the copyright notice is left unchanged.
'
' Code Courtesy of
' Dev Ashish
'
Private Declare Function apiShellExecute Lib "shell32.dll" _
    Alias "ShellExecuteA" _
    (ByVal hwnd As Long, _
    ByVal lpOperation As String, _
    ByVal lpFile As String, _
    ByVal lpParameters As String, _
    ByVal lpDirectory As String, _
    ByVal nShowCmd As Long) _
    As Long

'***App Window Constants***
Public Const WIN_NORMAL = 1         'Open Normal
Public Const WIN_MAX = 3            'Open Maximized
Public Const WIN_MIN = 2            'Open Minimized

'***Error Codes***
Private Const ERROR_SUCCESS = 32&
Private Const ERROR_NO_ASSOC = 31&
Private Const ERROR_OUT_OF_MEM = 0&
Private Const ERROR_FILE_NOT_FOUND = 2&
Private Const ERROR_PATH_NOT_FOUND = 3&
Private Const ERROR_BAD_FORMAT = 11&

'***************Usage Examples***********************
'Open a folder:     ?fHandleFile("C:TEMP",WIN_NORMAL)
'Call Email app:    ?fHandleFile("mailto:dash10@hotmail.com",WIN_NORMAL)
'Open URL:          ?fHandleFile("http://home.att.net/~dashish", WIN_NORMAL)
'Handle Unknown extensions (call Open With Dialog):
'                   ?fHandleFile("C:TEMPTestThis",Win_Normal)
'Start Access instance:
'                   ?fHandleFile("I:mdbsCodeNStuff.mdb", Win_NORMAL)
'****************************************************

Function fHandleFile(stFile As String, lShowHow As Long)
Dim lRet As Long, varTaskID As Variant
Dim stRet As String
    'First try ShellExecute
    lRet = apiShellExecute(hWndAccessApp, vbNullString, _
            stFile, vbNullString, vbNullString, lShowHow)

    If lRet > ERROR_SUCCESS Then
        stRet = vbNullString
        lRet = -1
    Else
        Select Case lRet
            Case ERROR_NO_ASSOC:
                'Try the OpenWith dialog
                varTaskID = Shell("rundll32.exe shell32.dll,OpenAs_RunDLL " _
                        & stFile, WIN_NORMAL)
                lRet = (varTaskID <> 0)
            Case ERROR_OUT_OF_MEM:
                stRet = "Error: Out of Memory/Resources. Couldn't Execute!"
            Case ERROR_FILE_NOT_FOUND:
                stRet = "Error: File not found.  Couldn't Execute!"
            Case ERROR_PATH_NOT_FOUND:
                stRet = "Error: Path not found. Couldn't Execute!"
            Case ERROR_BAD_FORMAT:
                stRet = "Error:  Bad File Format. Couldn't Execute!"
            Case Else:
        End Select
    End If
    fHandleFile = lRet & _
                IIf(stRet = "", vbNullString, ", " & stRet)
End Function
'************ Code End **********

Just put this into a separate module and call fHandleFile() with the right parameters.

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

01.08.2020 00:56

Создание простейшего браузера средствами VBA с возможностью парсинга сайтов

Рассматривается создание и применение простейшего браузера, созданного в качестве макроса в MS Excel на языке VBA с возможностью парсинга сайтов.
Ключевые слова: парсинг, браузер, синтаксический анализ, Excel, макрос, программирование, сайт.

Многим пользователям приходится пользоваться устаревшими компьютерами с ограниченными ресурсами. Это не позволяет им полноценно пользоваться сетью Интернет и значительно замедляет работу. Для полноценной работы нужен браузер, который состоит из минимального количества компонентов и имеет возможность получать список всех ссылок сайта, в том числе и ссылки на все файлы, которые находятся на странице, что существенно сокращает время поиска нужной информации.

Для решения этой проблемы поставлена цель создать браузер на языке Visual Basic for Applications с минимальными системными требованиями, интегрированный в MS Excel с возможностью парсинга сайтов.

Парсинг сайтов — последовательный синтаксический анализ информации, размещённой на интернет-страницах.

Это, в свою очередь, позволит решить следующие задачи:
— Освоить возможности VBA
— Научиться подключать библиотеку динамических модулей (IE)
— Включить в проект основные компоненты и интерфейсы браузера
— Осуществление доступа к объектам через компоненты в цикле
— Осуществить извлечение ссылок на файлы-архивы, файлы-документы с HTML-страницы

Создание браузера начинается с выявления потребностей пользователей: выбора дизайна, интерфейса и т. п.

Для начала требуется выбрать, в каком виде должен быть выполнен данный браузер. Так как должно выполняться извлечение ссылок, наилучшей возможностью представляется выполнение браузера в виде макроса в MS Excel.

Какими же необходимыми функциями должен обладать будущий браузер?

В окне должны быть следующие компоненты:
— поле для ввода и отображения адреса сайта;
— выпадающий список с важными ресурсами;
— кнопка начала загрузки страницы;
— кнопка остановки загрузки страницы;
— кнопка обновления страницы;
— кнопки «Вперед», «Назад», «Домой»;
— кнопка для запуска парсинга (извлечение ссылок);
— Окно для отображения сайта.

Наш браузер использует динамические библиотеки браузера Internet Explorer, что упрощает его создание и значительно уменьшает появление ошибок.

После выбора дизайна и разработки проекта можно приступить к написанию программного кода. Он состоит из множества блоков:
— Объявляются переменные, функции
Dim mo Resizer As New C Form Resizer
Dim status D As Boolean
Dim ff As Integer
— Блок, где процедура запускает новый InternetExplorer, создает и инциализирует глобальный объект InternetExplorerWith Events, инициализирует глобальную переменную gblnInternet Ex- plorerIs Open для контроля открытого состояния InternetExplorer
Public Sub Internet Explorer Open (bln Silent As Boolean, _
Bln Visible As Boolean)
— Процедура вызывает метод Navigate для открытия необходимой Web-страницы и сохраняет URL в глобальной переменной.
Public Sub Internet Explorer Navigate (By Valstr URL As String)
— Процедура вызывается событием Document Comlete, сравнивает URL загруженной страницы, создает объект HTML Document и выполняет необходимые действия с содержимым Web-страницы
Public Sub Document Comlete (var URL As Variant)

При работе с браузером происходит следующее — пользователь ввел URL, происходит попытка перейти по указанному адресу, если блок с условием отсутствия ошибок выполняется положительно, осуществляется переход на страницу. При нажатии на кнопку «Парсинг» происходит извлечение всех ссылок, которые находятся на открытой странице в браузере. Эти ссылки записываются в ячейки Excel столбиком.

В итоге получился браузер, состоящий из минимального количества компонентов. Интегрированный набор требует меньше системных ресурсов, чем все его компоненты в своих независимых модификациях, осуществлена возможность парсинга сайтов. Есть перспективы на дальнейшую доработку. Возможности данного браузера очень обширны. Это позволяет пользоваться им не только обычным пользователям, но и веб-программистам и веб-дизайнерам для анализа сайтов, хакерам и т. д.

Список использованной литературы
1. Ермошин А. В., Иванов В. В., Монахов М. Ю., Монахова Г. Е. Индивидуально-ориентированное обучение компьютерной графике в вузе. URL: http://elibrary.ru/download/34326150.pdf
2. Зайцева С. А., Иванов В. В. Формирование компетентности студентов в области информационных и коммуникационных технологий средствами дисциплин профессиональной подготовки. URL: http://elibrary.ru/download/60275857.pdf
3. Основы программирования VBA. URL: http://www.lessons- tva.info/edu/e-inf2/m2t3_7.html. (дата обращения: 14.09.2016).
4. Введение в VBA, макросы, программирование в Excel. URL: http://4excel.ru/index.php?id=vba1. (дата обращения: 14.09.2016).

В. С. Киселев

Опубликовано 01.08.2020 00:56 | Просмотров: 973 | Блог » RSS

Like this post? Please share to your friends:
  • Ввожу цифры в excel
  • Вводу формулы в ячейке в ms excel должно предшествовать нажатие клавиши
  • Вводишь адрес в excel
  • Вводить формулы в excel можно с помощью
  • Вводить по русски excel