Vba excel google chrome

I found an easier way to do it and it works perfectly even if you don’t know the path where the chrome is located.

First of all, you have to paste this code in the top of the module.

Option Explicit
Private pWebAddress As String
Public Declare Function ShellExecute 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

After that you have to create this two modules:

Sub LoadExplorer()
    LoadFile "Chrome.exe" ' Here you are executing the chrome. exe
End Sub

Sub LoadFile(FileName As String)
    ShellExecute 0, "Open", FileName, "http://test.123", "", 1 ' You can change the URL.
End Sub

With this you will be able (if you want) to set a variable for the url or just leave it like hardcode.

Ps: It works perfectly for others browsers just changing «Chrome.exe» to opera, bing, etc.

What is Data Scraping using selenium?

Selenium can be classified as the automation tool that facilitates scraping of information from the HTML web pages to perform web scraping utilizing google chrome.

How to prepare Excel Macro before performing Data Scraping using Selenium?

There are certain prerequisites that has to be performed on the excel macro file before getting into the process of data scraping in excel.

These prerequisites are as follows: –

Step 1) Open an Excel-based Macro and access the developer option of excel.

Step 2) Select Visual Basic option under Developer ribbon.

Step 3) Insert a new module.

Step 4) Initialize a new subroutine and name it as test2.

Sub test2()
End sub

Following would be the results in the module: –

Step 5) Access the reference option under the tool tab and reference Selenium type library. The following libraries are to be referenced to the module as it helps in opening google chrome and facilitates the development of macro scripting.

Now the Excel file is ready to interact with the internet explorer. Next steps would be to incorporate a macro script that would facilitate data scraping in HTML.

How to Open Google Chrome using VBA?

Here, are step to open Google Chrome using VBA

Step 1) Declare and initialize the variables in the subroutine as displayed below

Sub test2()
Dim driver as new webdriver
Dim rowc, cc, columnC as integer

Step 2) To open google chrome using selenium and VBA, write driver.start “chrome” and press F5.

The following would be the code.

Sub test2()
Dim driver as new webdriver
Dim rowc, cc, columnC as integer
Driver.start "Chrome"
Application.Wait Now+Timevalue("00:00:20")
End sub

The module would result as follows: –

How to Open Website in Google chrome using VBA?

Once you are able to access the google chrome using VBA, the next step would be to incorporate the accessing of a website using VBA. This facilitated by get function wherein the URL has to pass as double quotes in the attribute.

Follow the following steps as displayed

The module would look as follows: –

Press F5 to execute the macro.

The following webpage would be opened in google chrome as displayed

Sub test2()
Dim driver as new webdriver
Dim rowc, cc, columnC as integer
Driver.start "Chrome"
Driver.get "http://demo.guru99.com/test/web-table-element.php"
Application.Wait Now+Timevalue("00:00:20")
End sub

Now the excel macro is ready with respect to performing the scraping tasks. The next step would display how the information can be extracted by applying selenium and VBA.

How to Scrape information from Website using VBA?

Suppose the day trader wants to access the data from the website on a daily basis. Each time the day trader presses the click the button, it should auto pull the market data into excel.

From the above website, it would be necessary to inspect an element and observe how the data is structured. Access the below source code of HTML by pressing control + Shift + I

<table class="datatable">
<thead>
<tr>
<th>Company</th>
<th>Group</th>
<th>Pre Close (Rs)</th>
<th>Current Price (Rs)</th>
<th>% Change</th>
</tr>

The source code would be as follows: –

As it can be seen that the data is structured as a single HTML Table. Therefore, in order to pull entire data from the HTML table, it would require designing of macro which pulls the header information of the HTML table and the corresponding data associated with the table. Perform the following tasks as displayed: –

Step 1) Formulate a for loop that runs through the HTML header information as a collection. The selenium driver has to find the header information of the HTML table. To do this, we utilize the FindElementByClass() and FindElementByTag() method to perform the task as displayed

The VBA module would look as follows: –

Sub test2()
Dim driver As New WebDriver
Dim rowc, cc, columnC As Integer
rowc = 2
Application.ScreenUpdating = False
driver.Start "chrome"
driver.Get "http://demo.guru99.com/test/web-table-element.php"
For Each th In driver.FindElementByClass("dataTable").FindElementByTag("thead").FindElementsByTag("tr")
cc = 1
For Each t In th.FindElementsByTag("th")
Sheet2.Cells(1, cc).Value = t.Text
cc = cc + 1
Next t
Next th

Step 2) Next, the selenium driver would locate the table data using the similar approach, as mentioned above. You have to write the following code: –

Sub test2()
Dim driver As New WebDriver
Dim rowc, cc, columnC As Integer
rowc = 2
Application.ScreenUpdating = False
driver.Start "chrome"
driver.Get"http://demo.guru99.com/test/web-table-element.php"
For Each th In driver.FindElementByClass("dataTable").FindElementByTag("thead").FindElementsByTag("tr")
cc = 1
For Each t In th.FindElementsByTag("th")
Sheet2.Cells(1, cc).Value = t.Text
cc = cc + 1
Next t
Next th
For Each tr In driver.FindElementByClass("dataTable").FindElementByTag("tbody").FindElementsByTag("tr")
columnC = 1
For Each td In tr.FindElementsByTag("td")
Sheet2.Cells(rowc, columnC).Value = td.Text
columnC = columnC + 1
Next td
rowc = rowc + 1
Next tr
Application.Wait Now + TimeValue("00:00:20")
End Sub

The vba module would look as follows: –

The excel can be initialized by means of the Range attribute of the excel sheet or through cells attribute of the excel sheet. To reduce the complexity of the VBA script, the collection data is initialized to the excel cells attribute of the sheet 2 present in the workbook. Further, the text attribute helps in getting the text information placed under HTML tag.

Sub test2()
Dim driver As New WebDriver
Dim rowc, cc, columnC As Integer
rowc = 2
Application.ScreenUpdating = False
driver.Start "chrome"
driver.Get"http://demo.guru99.com/test/web-table-element.php"
For Each th In driver.FindElementByClass("dataTable").FindElementByTag("thead").FindElementsByTag("tr")
cc = 1
For Each t In th.FindElementsByTag("th")
Sheet2.Cells(1, cc).Value = t.Text
cc = cc + 1
Next t
Next th
For Each tr In driver.FindElementByClass("dataTable").FindElementByTag("tbody").FindElementsByTag("tr")
columnC = 1
For Each td In tr.FindElementsByTag("td")
Sheet2.Cells(rowc, columnC).Value = td.Text
columnC = columnC + 1
Next td
rowc = rowc + 1
Next tr
Application.Wait Now + TimeValue("00:00:20")
End Sub

The vba module would look as follows: –

Step 3) Once the macro script is ready, pass and assign the subroutine to excel button and exit the module of VBA. Label the button as refresh or any suitable name that could be initialized to it. For this example, the button is initialized as refresh.

Step 4) Press the refresh button to get the below mentioned output

Step 5) Compare the results in excel with the results of google chrome

Summary:

  • Selenium can be classified as the automation tool that facilitates scraping of information from the HTML web pages to perform web scraping utilizing google chrome.
  • The scraping on the internet should be performed carefully.
  • It is normally against the terms of the website to scrape out information.
  • When scraping is done through selenium, then it offers multiple browser support.
  • In other words, the scraper can perform similar tasks of scraping through Firefox, internet explorer as well.

Home / VBA / How to Search on Google using a VBA Code

There are a lot of important things which we all do other than using Excel.

Am I right?

One of those things is using Google to search for something. In my list of useful macro codes, I have a code which you can use to perform a search query on Google using Chrome.

And today, I’m going to share that code with you. You can add this code to your personal macro workbook and use it anytime when you need to search for something on Google.

VBA Code to Open Google Chrome for Search

Here is the code below which you can use to search on Google using Chrome.

Window 32 Version

Sub Google_Search_32()
Dim chromePath As String
Dim search_string As String
Dim query As String
query = InputBox("Enter here your search here", "Google Search")
search_string = query
search_string = Replace(search_string, " ", "+")
chromePath = """C:Program Files (x86)GoogleChromeApplicationchrome.exe"""
Shell (chromePath & " -url http://google.com/search?q=" & search_string)
End Sub

Window 64 Version

Sub Google_Search_64()
Dim chromePath As String
Dim search_string As String
Dim query As String
query = InputBox("Enter here your search here", "Google Search")
search_string = Replace(query, " ", "+")
chromePath = """C:Program FilesGoogleChromeApplicationchrome.exe"""
Shell (chromePath & " -url http://google.com/search?q=" & search_string)
End Sub

How to use this VBA Code to Search on Google

Here are the simple step you need to follow to use this code.

  • Open VB editor using shortcut key Alt + F11 or go to developer tab.
  • Insert a new module in and paste above code into it.  

Now, close VB editor and run this macro from macros option in developer tab.

How it works

When you run this code it shows you an input box to enter your query. And you need to enter your query in that input box and click OK.

Once you click OK, this code creates a search URL syntax using the text you have entered.

And, in the end redirects Chrome to that URL to give you result for query you have entered.

More VBA Codes to Try

  • ON-OFF Button in Excel
  • A List of 100 Macro Codes
  • Macro Code to Create a Pivot Table
  • Record a Macro
  • Option Explicit in VBA

Я нашел более простой способ сделать это, и он отлично работает, даже если вы не знаете, где находится хром.

Прежде всего, вы должны вставить этот код в верхнюю часть модуля.

Option Explicit
Private pWebAddress As String
Public Declare Function ShellExecute 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

После этого вам нужно создать эти два модуля:

Sub LoadExplorer()
    LoadFile "Chrome.exe" ' Here you are executing the chrome. exe
End Sub

Sub LoadFile(FileName As String)
    ShellExecute 0, "Open", FileName, "http://test.123", "", 1 ' You can change the URL.
End Sub

Благодаря этому вы сможете (если хотите) установить переменную для URL-адреса или просто оставить ее как жесткий код.

Ps: Он отлично работает для других браузеров, просто меняя «Chrome.exe» на opera, bing и т. Д.

Now the Excel file is ready to interact with the internet explorer. Next steps would be to incorporate a macro script that would facilitate data scraping in HTML.

Here, are step to open Google Chrome using VBA

Step 1) Declare and initialize the variables in the subroutine as displayed below

Sub test2()
Dim driver as new webdriver
Dim rowc, cc, columnC as integer

Step 2) To open google chrome using selenium and VBA, write driver.start “chrome” and press F5.

Ниже будет код.

Sub test2()
Dim driver as new webdriver
Dim rowc, cc, columnC as integer
Driver.start "Chrome"
Application.Wait Now+Timevalue("00:00:20")
End sub

Модуль будет выглядеть следующим образом:

Нажмите F5, чтобы выполнить макрос.

Теперь макрос Excel готов к выполнению задач очистки. На следующем шаге будет показано, как можно извлечь информацию, применяя селен и VBA.

Предположим, что дневной трейдер хочет ежедневно получать доступ к данным с веб-сайта. Каждый раз, когда дневной трейдер нажимает кнопку, он должен автоматически вытягивать рыночные данные в Excel.

На указанном выше веб-сайте необходимо будет проверить элемент и посмотреть, как структурированы данные. Получите доступ к приведенному ниже исходному коду HTML, нажав control + Shift + I

<table class="datatable">
<thead>
<tr>
<th>Company</th>
<th>Group</th>
<th>Pre Close (Rs)</th>
<th>Current Price (Rs)</th>
<th>% Change</th>
</tr>

Исходный код будет следующим:

Как видно, данные структурированы как единая таблица HTML. Следовательно, для извлечения целых данных из таблицы HTML потребуется разработка макроса, который извлекает информацию заголовка таблицы HTML и соответствующие данные, связанные с таблицей. Выполните следующие задачи, как показано: –

Шаг 1) Сформулируйте цикл for, который просматривает информацию заголовка HTML в виде коллекции. Драйвер селена должен найти информацию заголовка таблицы HTML. Для этого мы используем метод FindElementByClass () и FindElementByTag (), чтобы выполнить задачу, как показано

Модуль VBA будет выглядеть следующим образом:

Sub test2()
Dim driver As New WebDriver
Dim rowc, cc, columnC As Integer
rowc = 2
Application.ScreenUpdating = False
driver.Start "chrome"
driver.Get "http://demo.guru99.com/test/web-table-element.php"
For Each th In driver.FindElementByClass("dataTable").FindElementByTag("thead").FindElementsByTag("tr")
cc = 1
For Each t In th.FindElementsByTag("th")
Sheet2.Cells(1, cc).Value = t.Text
cc = cc + 1
Next t
Next th

Шаг 2) Затем драйвер селена найдет данные таблицы, используя аналогичный подход, как упомянуто выше. Вы должны написать следующий код: –

Sub test2()
Dim driver As New WebDriver
Dim rowc, cc, columnC As Integer
rowc = 2
Application.ScreenUpdating = False
driver.Start "chrome"
driver.Get"http://demo.guru99.com/test/web-table-element.php"
For Each th In driver.FindElementByClass("dataTable").FindElementByTag("thead").FindElementsByTag("tr")
cc = 1
For Each t In th.FindElementsByTag("th")
Sheet2.Cells(1, cc).Value = t.Text
cc = cc + 1
Next t
Next th
For Each tr In driver.FindElementByClass("dataTable").FindElementByTag("tbody").FindElementsByTag("tr")
columnC = 1
For Each td In tr.FindElementsByTag("td")
Sheet2.Cells(rowc, columnC).Value = td.Text
columnC = columnC + 1
Next td
rowc = rowc + 1
Next tr
Application.Wait Now + TimeValue("00:00:20")
End Sub

Модуль VBA будет выглядеть следующим образом:

Excel можно инициализировать с помощью атрибута Range листа Excel или с помощью атрибута ячейки листа Excel. Чтобы уменьшить сложность сценария VBA, данные сбора инициализируются атрибутом ячеек Excel листа 2, представленного в рабочей книге. Кроме того, атрибут text помогает получить текстовую информацию, размещенную под тегом HTML.

Sub test2()
Dim driver As New WebDriver
Dim rowc, cc, columnC As Integer
rowc = 2
Application.ScreenUpdating = False
driver.Start "chrome"
driver.Get"http://demo.guru99.com/test/web-table-element.php"
For Each th In driver.FindElementByClass("dataTable").FindElementByTag("thead").FindElementsByTag("tr")
cc = 1
For Each t In th.FindElementsByTag("th")
Sheet2.Cells(1, cc).Value = t.Text
cc = cc + 1
Next t
Next th
For Each tr In driver.FindElementByClass("dataTable").FindElementByTag("tbody").FindElementsByTag("tr")
columnC = 1
For Each td In tr.FindElementsByTag("td")
Sheet2.Cells(rowc, columnC).Value = td.Text
columnC = columnC + 1
Next td
rowc = rowc + 1
Next tr
Application.Wait Now + TimeValue("00:00:20")
End Sub

Модуль VBA будет выглядеть следующим образом:

Шаг 3) Как только макрос-скрипт будет готов, передайте и назначьте подпрограмму для кнопки Excel и выйдите из модуля VBA. Пометьте кнопку как обновление или любое подходящее имя, которое можно инициализировать. В этом примере кнопка инициализируется как обновление.

Excel VBA to Automate Chrome using Selenium

In this topic we will learn how to install Selenium library in Windows PC & initiate Chrome browser.

Selenium is a free open source framework that help in testing & automating web applications in browser.

Many programmers use this for automated web data extraction like stock quotes, sports betting , new updates, social media feeds, public directories etc., that refresh data periodically.

Steps to add Selenium type library to Excel VBA for Windows PC

Follow this step by step process carefully to learn Web Data extraction basics.

If you miss even a tiny detail, the process might fail to launch Chrome or extract data from the web browser.

1.Selenium VBA Download

To Automate Chrome browser with Excel VBA, first step is to download and install Selenium type library from this page:

  • Selenium download page.

Download the latest version & the one that is compatible for your Windows OS type. Install this to add Selenium library for Excel VBA.

2. Google Chrome Browser Version

From Chrome settings, check for version of the browser installed (chrome://settings/help)

  • Sample: Version 91.0.4472.77 – Official Build 64-bit

It is a older version mentioned above. In your PC, it could be a advanced version.

3. Chromedriver Download

The next and final software required for Selenium to to work is Chromedriver.

Go to this Google sites page and download version Zip version of Chromedriver relative to the Chrome installed in your pc:

  • Latest Chrome driver download page
  • Use this link to download older version of Chrome driver

Do not run the exe file inside this zip folder. Follow the steps explained below.

4. Setup Chromedrver Folder

Extract Chromedriver.exe from Zip file downloaded in previous step & replace the chromedriver.exe in below path.

  • C:Users%username%AppDataLocalSeleniumBasic

A file with same name might be present already in this folder. Rename it to Chromedriverbkp.exe and then extract the latest file from zip to this folder.

Add Selenium Reference to Excel VBA

The installation step is done. Selenium library is installed in your PC and should be available within Excel VBA environment.

Lets find it out whether everything went fine till now.

5. Add reference to Excel VBA Selenium Type Library 

Open a Excel file, save it as .xlsm file, press Alt + F11 to view VBA editor. Then add selenium to Excel VBA project from this menu option.

  • Tools – References – Selenium Type Library

6. Sample Code – Excel VBA Selenium Chrome

Add a new module, copy paste this code to EXcel VBA editor. When you run the code, you wil be able to see a Chrome browser is getting opened, opens the url & then gets closed.

Sub InitBrowser()
    Dim objChrome As New Chromedriver
    objChrome.SetProfile "C:Users<getUserName>AppDataLocalGoogleChromeUser DataDefault"
    objChrome.Start "chrome", "https://www.google.com"
    objChrome.Get "/"
End Sub

Note: If you would like the browser to stay after the code gets executed, define the “objChrome” as a global variable outside the function.

How to Install Excel VBA Selenium Type Library – Tutorial

Here is a video tutorial that explains all these steps in detail.

Also, you can choose to mention the username for the profile manually or make the VBA to get the active username and will it automatically.

This is a basic step for extracting webdata using Chrome using Excel VBA. In case you would like to extract web data without using Chrome for simple static pages, use this code.

Once you understand this basic concepts, then from here on it is easy to get the HTML code of any web page. Then you can use the built in functions available within Selenium type library & prase the data to Excel worksheet.

It is also possible to send data back to Chrome. Therefore it is easy to automate a whole lot of operations like Form filling, clicking a button, apply search criteria filters in any webpage. So, overall, selenium is a great option to automate chrome and alos other browsers like Firefox & Edge.

Hi Andrew,

Subsequent to my earier post, i made some adjustments. I am still stuck at how to get the output data into one results sheet in the pivot table format. Your assistance would be greatly appreciated. The sample input data is valid for this code. 

Thanks much!

Option Explicit

Private chromebrowser As Selenium.ChromeDriver ‘ declaration at the module level. note we changed DIM to Private

Sub LoopScrapePropTaxWebsiteNew()

Dim FindBy As New Selenium.By ‘ declaration of an auto instancing BY object to query any changes to HTML class name

Dim PropertyOwnerQueryResults As Selenium.WebElements ‘ Declaration of a variable that can take multiple web elements
Dim PropertyTaxResults As Selenium.WebElements   ‘ Declaration of a variable that can take only one web element
Dim PropertyOwnerQueryResult As Selenium.WebElement
Dim PropertyTaxResult As Selenium.WebElement
Dim PropInfoTable As Selenium.WebElement
Dim PropTaxtable As Selenium.WebElement
Dim ValNo As String
Dim StratNo As String

Set chromebrowser = New Selenium.ChromeDriver

chromebrowser.Start ‘The base URL in google chrome
chromebrowser.Get «https://ptsqueryonline.fsl.org.jm/PTSOnlineWeb/ptsquery.jsp» ‘ access the home page. If we wanted to access any page, we would just indicate the page name after the forward slash

Application.ScreenUpdating = False  ‘This line will turn off the screen flickering

Worksheets(«PropTaxData»).Activate ‘ Go back to the property Tax Sheet
Range(«A2»).Select

    
‘————Loop to download the Property Tax Information

    
    Do Until ActiveCell.Value = «»

        
        ValNo = ActiveCell.Value
        StratNo = ActiveCell.Offset(0, 1).Value

        
    If chromebrowser.IsElementPresent(FindBy.Name(«valuationno»), 5000) = False Then ‘ this is to account for any changes in class name as time passes. the number is the timeout period in millisecond, ie 3000 milliseconds is 3 sec
        chromebrowser.Quit ‘ code to exit the chrome browser
        MsgBox «Could not find search input box», vbExclamation  ‘ Code to diplay message box with error
        Exit Sub  ‘ Exit sub routine
    End If ‘ end if statement

    chromebrowser.FindElementByName(«valuationno»).SendKeys ValNo

    If chromebrowser.IsElementPresent(FindBy.Name(«stratalotno»), 5000) = False Then ‘ this is to account for any changes in class name as time passes. the number is the timeout period in millisecond, ie 3000 milliseconds is 3 sec
        chromebrowser.Quit ‘ code to exit the chrome browser
        MsgBox «Could not find search input box», vbExclamation  ‘ Code to diplay message box with error
        Exit Sub  ‘ Exit sub routine
    End If ‘ end if statement

    chromebrowser.FindElementByName(«stratalotno»).SendKeys StratNo

    If chromebrowser.IsElementPresent(FindBy.Class(«btn»), 5000) = False Then ‘ this is to account for any changes button name as time passes. the number is the timeout period in millisecond, ie 3000 milliseconds is 3 sec
        chromebrowser.Quit ‘ code to exit the chrome browser
        MsgBox «Could not find submit button», vbExclamation  ‘ Code to diplay message box with error
        Exit Sub  ‘ Exit sub routine
    End If ‘ end if statement

    chromebrowser.FindElementByClass(«btn», 3000).Click

‘—————Retriving the results of the property tax query

    Set PropertyOwnerQueryResults = chromebrowser.FindElementsByClass(«form-horizontal»)

    If PropertyOwnerQueryResults.Count = 0 Then      ‘ Condition to account for an empty result set
        ‘chromebrowser.Quit
        MsgBox «No Results Found» & » » & «for Valuation No» & » » & ValNo, vbExclamation
        Exit Sub
    End If

        For Each PropertyOwnerQueryResult In PropertyOwnerQueryResults ‘ loops through the web elements

            Set PropInfoTable = PropertyOwnerQueryResult.FindElementByTag(«tbody»)
             ‘Debug.Print PropInfoTable.Text ‘ print the webeleemnt texts to the immediate window

             
        Next PropertyOwnerQueryResult

    ProcessTable PropInfoTable

    
    chromebrowser.FindElementById(«back»).Click ‘Select the back button

     
    Worksheets(«PropTaxData»).Activate

        
    ActiveCell.Offset(1, 0).Select ‘ Go to the next cell

    
    Loop

    
    ‘Application.ScreenUpdating = True

End Sub

Sub ProcessTable(TableToProcess As Selenium.WebElement)

    Dim AllRows As Selenium.WebElements
    Dim SingleRow As Selenium.WebElement
    Dim AllRowCells As Selenium.WebElements
    Dim SingleCell As Selenium.WebElement
    Dim OutputSheet As Worksheet
    Dim RowNum As Long, ColNum As Long
    Dim TargetCell As Range
    

    Set OutputSheet = ThisWorkbook.Worksheets(«Results»)

    
    Set AllRows = TableToProcess.FindElementsByTag(«tr»)

    For Each SingleRow In AllRows

    
        RowNum = RowNum + 1
        Set AllRowCells = SingleRow.FindElementsByTag(«td»)

        
        If AllRowCells.Count = 0 Then
            Set AllRowCells = SingleRow.FindElementsByTag(«th»)
        End If

        
        For Each SingleCell In AllRowCells

        
            ColNum = ColNum + 1

            
            Set TargetCell = OutputSheet.Cells(RowNum, ColNum)

            
            TargetCell.Value = SingleCell.Text

            
            ‘Debug.Print SingleCell.Text
        Next SingleCell

    
        ColNum = 0

        
    Next SingleRow

End Sub

I’m trying to open a Chrome browser from VBA. I understand Chrome does not support ActiveX settings so I’m curious if theres any work-arounds?

Dim ie As Object 
Set ie = CreateObject("ChromeTab.ChromeFrame")
ie.Navigate "google.ca" 
ie.Visible = True

Answer

shell("C:UsersUSERNAMEAppDataLocalGoogleChromeApplicationChrome.exe -url http:google.ca")

Attribution
Source : Link , Question Author : Sam , Answer Author : ray

Related

Is there a way how to open Chrome on VBA.

Hello

I’m trying to import website tables to Excel and I have written a VBA code but it doesn’t work and I don’t have the idea why, also I want to make VBA to open on Chrome not in IE, below I will paste my code and if someones know, I would appreciate if he can make some changes.

Sub SIMPLEDATAEXTRACTION()
Dim IE As Object
Set IE = CreateObject(«Internetexplorer.Application»)
IE.Visible = True
IE.navigate «ti.com/data-converters/adc-circuit/products.html»
Do While IE.busy Or IE.readystate <> 4
DoEvents
Loop
ce = 1

For Each td In IE.document.getElementsbyTagName(«tr»)
Range(«A» & ce).Value = td.Children(0).innertext
Range(«B» & ce).Value = td.Children(1).innertext
Range(«C» & ce).Value = td.Children(2).innertext
Range(«D» & ce).Value = td.Children(3).innertext
Range(«E» & ce).Value = td.Children(4).innertext
Range(«F» & ce).Value = td.Children(5).innertext
Range(«G» & ce).Value = td.Children(6).innertext
Range(«H» & ce).Value = td.Children(7).innertext
Range(«I» & ce).Value = td.Children(8).innertext
Range(«J» & ce).Value = td.Children(9).innertext
Range(«K» & ce).Value = td.Children(10).innertext
Range(«L» & ce).Value = td.Children(11).innertext
Range(«M» & ce).Value = td.Children(12).innertext
Range(«N» & ce).Value = td.Children(13).innertext

ce = ce + 1
Next td
End Sub

Понравилась статья? Поделить с друзьями:
  • Vba excel get range address
  • Vba excel get hyperlink
  • Vba excel get all rows
  • Vba excel function пример
  • Vba excel function as array in