Browser automation in Excel VBA using Selenium

When it comes to browser automation tasks in Excel VBA like filling a web form, login to a website etc. most of them use Internet explorer by adding a reference to Microsoft Internet controls.

VBA users have been using IE automation from many years and most of them still use it. but there is a problem with Internet explorer! As we all know Internet explorer is the ‘God of all browsers’ – I mean we just use it to download other browsers because of its performance issues. Due to its poor performance automation also would be slow.


Then why not use high performance browsers like chrome or firefox? Yes this post is all about browser automation in VBA using selenium VBA wrapper which enables automating high performance browsers like chrome and firefox with just few lines of code.

What is Selenium

Selenium is a testing framework. Selenium automates browsers. That’s it! What you do with that power is entirely up to you. Primarily, it is for automating web applications for testing purposes, but is certainly not limited to just that. Boring web-based administration tasks can (and should!) also be automated as well.
Some good guy has written a .net wrapper for selenium which can be used in VBA and and that is the wrapper we are going to use in this tutorial.

Prerequisites :
  1. Basic knowledge of VBA
  2. Microsoft Excel installed in windows OS – Selenium VBA wrapper is a windows COM library so it works only on windows.
  3. Selenium VBA wrapper library – you can download and install it from here

Getting started with selenium VBA

1.Open any excel file, go to code editor (Alt + f11) and create a sub.

Public Sub seleniumtutorial()

End Sub

2.Add selenium VBA reference
go to tools > references > check ‘Selenium Type Library’ and click ok.

3.Define and start web driver
selenium web driver is what controls the browser.
syntax : Dim drivername as new WebDriver

 Dim bot as new WebDriver 

This driver is used to start and automate the browser.

4.Start browser
A browser can be started by using start method of webdriver.
syntax : driver.Start "browsername", "baseurl"
currently supports chrome, firefox, opera, PhantomJS & IE

bot.Start "chrome", ""
Simple example

Lets say we have to open a website and take screenshot of it. This can be done in just 2 lines of code. open website using Get method and screenshot using TakeScreenshot method

Public Sub seleniumtutorial()
Dim bot As New WebDriver
bot.Start "chrome", ""
bot.Get "/"
bot.TakeScreenshot.SaveAs (ActiveWorkbook.Path + "/screenshot.jpg")
'quit method for closing browser instance.
End Sub

Above code is self explanatory, when you run this code a screenshot of website is saved in the folder in which current excel file is present.
Too easy right! But who wants a screenshot of google? Ah yes, this simple example is used just to explain the steps in automation. I’ll be explaining few practical situations of automation later in this tutorial.

Adding more functionality

Lets say I’m an SEO analyst, I want to search few words on google and take screenshot of results. List of keywords are in column A of keywords sheet.


Lets start by adding a sub

Public Sub keywordsearch()

End Sub

1.Define WebDriver and a Range to get range of keywords.

Dim bot As New WebDriver, rng As Range

2.set range to list of cells in column A

Set rng = Range(Worksheets("keywords").Range("A2"), Worksheets("keywords").Range("A2").End(xlDown))

Above code makes setting a range dynamic because of End(xlDown)
End(xlDown) = next non empty cell in that row (the cell you reach when you press ctrl + down in excel)

3.Start web driver

bot.Start "chrome", ""

4.Loop through each cell in range, search keyword in google

For Each cell In rng
bot.Get "/"
bot.FindElementByName("q").SendKeys (cell.Value)
bot.Wait 1000
bot.TakeScreenshot.SaveAs (ActiveWorkbook.Path + "/screenshot_" + cell.Value + ".jpg")

In the above code, First we use For to loop through each cell then get ‘/’ which is homepage, if we need image search then ‘/images’ is used. After loading homepage, find input textbox to enter the search word.

Selenium has many methods to find a html element, Most commonly used methods to find elements are FindElementById, FindElementByName, FindElementByXpath

To find a HTML element, we need a selector. selector may be ID or name or Xpath or class or tag. If we have ID then FindElementById is used, FindElementByName is used if we have name of the element and so on. Finding a selector is simple, just go that webpage > right click on the element for which we need a selector > Inspect element. Prefer ID first, if there is no ID or name then copy xpath by right clicking again on the element.


As you can see in the image above, input textbox on google homepage has name attribute so we can use FindElementByName to find element and SendKeys method to type the keyword in textbox.

Button also has a name attribute with value “btnG” so FindElementByName is used again to find the search button and click it using Click method.

Wait for 1 second for search to complete and then take a screenshot using TakeScreenshot method , moving to next cell and finally quit driver using Quit method.

Noteworthy methods :
  1. All FindElement methods
  2. ExecuteScript – used to run any custom Javascript code.
  3. IsElementPresent (Removed now)
  4. PageSource
  5. refresh
  6. until
  7. Proxy
  8. Window

These are the commonly used methods in selenium, give it a try.

Wait for element in Selenium VBA

In previous versions of Selenium wrapper, There were few methods like IsElementPresent and WaitForElementPresent which were used to check if element is present, wait till element is available. But these methods are removed now. So How do we wait for elements?

Current methods which are used to identify elements such as FindElementById, FindElementByXPath have an implicit wait of 3 seconds which means – If the element was not found initially then these methods wait for up to 3 seconds to see element becomes available.

If you just want to wait till element becomes available then just increase the implicit wait time of these methods using :

driver.FindElementById("someId", timeout:=10000) 'waits for up to 10 seconds
driver.FindElementById("someId", timeout:=20000) 'waits for up to 20 seconds

Check is element is present in Selenium VBA

If your goal is to just check if element is present or not instead of waiting for the element then it can be done using :

Set myelement = bot.FindElementById("someId", timeout:=0, Raise:=False)
If myelement Is Nothing Then
MsgBox ("no element found")
End If
My Practical use cases of selenium VBA

I had an excel list in my office which contains usernames and passwords of around 200 clients which are used to login to a web admin panel. whenever I need some information, I had to login manually by copying the username & password of that particular client and pasting in the browser and login. So I just wrote some code for autologin, used a shortcut key for that sub. whenever I wanted to login, I just click on the client name and used my shortcut key!

Fetching youtube channel subscribers count. This can be does using XML HTTP requests also. comment below if you want to know more about fetching data using XML HTTP.

Automating product purchases, few other automations which need browser involvement exclusively.

Update : Checkout next part of this tutorial Scrape website using Selenium VBA to learn how to scrape website data using selenium VBA and best practises of scraping data in excel.

Wrapping up

This was a quick tutorial, there is lot more that can be done with selenium VBA. you can download official examples file here which contains lot of examples on Selenium VBA automations. have a look at them and start automating!

If you have any questions or feedback, please comment below.

Need some help? Post your questions on our forum

Liked this post? Join our newsletter to get more stuff like this in your inbox.

Author: Ranjith kumar

A CA student by education, self taught coder by passion, loves to explore new technologies and believes in learn by doing.

36 Thoughts

  1. Hi Ranjith,
    I was using IE for browser automation.
    Can you help me doing a little conversion of my IE code for selenium so it clears me.
    Is it possible I can send you an excel file via email with code?
    Many thanks for your help


  2. Nice article, well described. I have been searching the web for an info closely related to this. I want to use to design a nice GUI of which the back end is to automate some mundane website tasks, seeing that it is possible to use selenium with VBA, I believe it should be possible to do with also, do you have an idea how I can go about this? Thanks in advance.

    1. Hello Mukhtar,

      Yes that can be done, Previously I have made few bots in using selenium. Best way to get started is using nuget package available here :

      If you are not familiar with using package manager then download Selenium web driver for .Net here :

      You can find it under C# language which is the same for too. Then add a reference to webdriver.dll and Import appropriate NameSpaces you need like
      Imports OpenQA.Selenium.Firefox
      Imports OpenQA.Selenium.Chrome

      By default, only firefox works without any additional driver. For chrome and other browsers you have to download appropriate drivers from the same link above. Hope that helps.

      1. Thanks Ranjith,

        I have realised where I was getting it wrong from your response. I didn’t find selenium download for before not knowing the same one for C# can be used for

  3. How to get the output in excel file. Code:
    Public Sub search()
    Dim bot As New WebDriver, rng As Range
    Set rng = Range(Worksheets(“keywords”).Range(“A2”), Worksheets(“keywords”).Range(“A2”).End(xlDown))
    bot.Start “chrome”, “”
    For Each Cell In rng
    bot.Get “/”
    bot.FindElementByName(“txt_Epicno”).SendKeys (Cell.Value)
    bot.Wait 5000
    End Sub
    I need your help.

      1. I need to get the details from the tamilnadu election website by clicking searchvoters and entering the voters epicno for ex : MSS3007457 it gives the all details of voters id . i need to save the details in excel format.all i need is the name,part no , slno and the voters constituency. I’ve voters epic number for checking in excel and i can only see the details in screen by running the macro which i learned from your site. The direct link is
        “”. can you help me in this regard.

        1. Hi, here’s code for scraping data of one voter :

          Public Sub scrapevoters()
          Dim bot As New WebDriver
          bot.Start “chrome”, “”
          bot.Get “/searchbyname.aspx”
          bot.FindElementById(“txt_Epicno”).SendKeys (“MSS3007457”)
          Sheets(1).Cells(1, 1).Value = bot.FindElementById(“lbnameen”).Text ‘Name
          Sheets(1).Cells(1, 2).Value = bot.FindElementById(“lbparten”).Text ‘Part number
          Sheets(1).Cells(1, 3).Value = bot.FindElementById(“lbserialen”).Text ‘Serial Number
          Sheets(1).Cells(1, 4).Value = bot.FindElementById(“lbpartnameen”).Text ‘Polling station
          End Sub

          Use it in a For loop to scrape multiple voters.
          bot.wait is not required here as it waits for page load automatically after click. Hope it helps.

          1. I’m able to loop through the following codes:
            Public Sub scrapevoters()
            Dim bot As New WebDriver, rng As Range, i As Integer
            Set rng = Range(Worksheets(“keywords”).Range(“A2”), Worksheets(“keywords”).Range(“A2”).End(xlDown))
            bot.Start “chrome”, “”
            For Each Cell In rng
            bot.Get “/”
            bot.FindElementByName(“txt_Epicno”).SendKeys (Cell.Value)
            i = i + 1
            Sheets(2).Cells(i, 2).Value = bot.FindElementById(“lbepicen”).Text
            Sheets(2).Cells(i, 3).Value = bot.FindElementById(“lbnameen”).Text
            Sheets(2).Cells(i, 4).Value = bot.FindElementById(“lbacnameen”).Text
            Sheets(2).Cells(i, 5).Value = bot.FindElementById(“lbparten”).Text
            Sheets(2).Cells(i, 6).Value = bot.FindElementById(“lbserialen”).Text
            Sheets(2).Cells(i, 7).Value = bot.FindElementById(“lbaden”).Text
            End Sub

            It works. Now here is the situation when the voters id is wrong then the page shows “Your Record is Not Available Now. For Further Enquiry Please Call 1950”. After the message looping stops. If the page doesnot display the records then it should go and fetch the next record. How to do it. sample voters list in my excel sheet BDZ2630614,BKH2950970,DDX2789360 and so on. the second record BKH2950970 gives “Your Record is Not Available Now. For Further Enquiry Please Call 1950”. how to loop through next record. Thanks

  4. Following codes inserted completes the looping:

    On Error Resume Next
    If Err.Number <> 0 Then
    Sheets(2).Cells(i, 2).Value = 0
    End If
    On Error GoTo 0
    But is there any other way to the solve the looping. Thanks

    1. Hi, The best way to handle this issue is to use IsElementPresent method on name element, check if element is present, then use goto next to continue loop if name element is not present.
      Name element would be present in every voter for sure and also rendered server side if epic number is found so using IsElementPresent method is the right way in this case but this method is buggy in the latest version of Selenium wrapper. So, Use the basic error handling that you mentioned above as a workaround for now. I would update you when IsElementPresent method is working fine.

  5. Hi,
    How to loop through select option and scrape data by each select options using selenium VBA .

  6. I ran the following and received this error. The Edge browser window opened but did not navigate to

    Public Sub seleniumtutorial()
    Dim bot As New WebDriver
    bot.Start “edge”, “”
    End Sub

    Error received: Run-time error ‘6’: NoSuchDriverError A session is either terminated or not started.

  7. Solved by updating the Edge driver:

    Copy “C:\Program Files (x86)\Microsoft Web Driver\MicrosoftWebDriver.exe”
    Rename it to edgedriver.exe
    Replace it in %LOCALAPPDATA%\SeleniumBasic

  8. Hi Ranjith, great article! I just found out about Selenium a few days ago and have been struggling to find an article with some well-explained examples of how to use Selenium. Do you mind if I email you about what I’m trying to accomplish using VBA and Selenium? I’m decent at VBA.

  9. I’m trying to use selenium to automate some work in Chrome. When I try to open chrome using the code below I get an error in chrome that says “You are using an unsupported command-line flag: –ignore-certificate-errors. Stability and security will suffer.”

    Sub OpenChrome()
    Dim selenium As New WebDriver
    selenium.Start “chrome”, “”
    selenium.setTimeout (“120000”)
    selenium.setImplicitWait (5000)
    End Sub

    I’ve built macros with VBA that automate work in internet explorer before, but I haven’t done it for chrome. It sounds like using selenium is the best way to build macros for navigating through chrome and interacting with the web. What am I doing wrong to get this error?

      1. Updated Selenium wrapper and now I’m getting this error:
        “Run-time error ’33’:

        session not created exception
        from unknown error: Runtime.executionContextCreated has invalid

        (Session info: chrome=54.0.2840.99)”

        Does this error look familiar?

        1. Okay, I tested it out with the latest version of selenium wrapper and got the same error. So I looked into the chrome driver version and found out that it’s v 2.21while the latest version with bug fixes for chrome 54 is v 2.25.

          Selenium wrapper installer comes with v 2.21 so we have to manually update the driver.

          First download chrome driver 2.25 from here – then go to your selenium path – C:\Users\username\AppData\Local\SeleniumBasic and replace the chrome driver with the latest one and it should work fine.

          I’ll make a request to update the chrome driver in selenium wrapper installer. Meanwhile, manual updating is the way to go.

          The beauty of development is – We got to stay ahead of everyone πŸ™‚

  10. Hi Ranjith,
    How do I use a conditional statement like below to find if an element is not present

    If driver.WaitNotElement(By.ID(“loadMore”))

    I get a “Type Mismatch Error”

    1. Hi Salam,

      If you are trying to check if Element is present or not then this code should do the work.

      Set mybutton = bot.FindElementById(“someid”, timeout:=0, Raise:=False)
      If mybutton Is Nothing Then
      MsgBox (“no element found”)
      End If

      But if you are trying to wait till the element becomes available the check the updated article. I’ve added a new section – Wait for element in Selenium VBA.

  11. I am very happy that i found your site finally. This site is awesome and very informative about different stuffs on complicated topics about which thousand others barely dare to deal with. Anyways, i got an issue in my written code. Gonna paste it underneath. Something is wrong with this. Every time i run it, i get an error showing “run time error 13, type mismatch”. By the way, i am running this code into my excel VBA editor.

    Here is the code:

    Any help would be greatly appreciated. Thanks in advance.

    1. I have already found the error and that is “driver.FindElementByClass(β€œinfo”)”, whereas the proper calling should be “driver.FindElementsByClass(β€œinfo”)”. By the way, can i run the code using seleniumwrapper.webdriver instead of webdriver.

    2. Hi Shahin, There are few mistakes in your code. Use FindElementsByClass instead of FindElementByClass in set posts line because there are multiple elements. Define posts and post as object instead of webelements.

      Here’s the working code –

      Seems like you are using an old version of Selenium VBA which has OPEN method. Install latest version and use GET method. Phantomjs is kind of unstable. It works sometimes, doesn’t work sometimes due to timeout issues. Use Chrome instead, It works perfectly. Also, try HTTP request method which I’ve used here – It will be 20 times faster than selenium πŸ™‚

Leave a Reply

Your email address will not be published. Required fields are marked *