6

I am on Windows 10.
I am trying to use Selenium to automate the Edge browser (or any other browser) via Excel VBA.

I went to https://www.selenium.dev/downloads/

There I downloaded
Selenium Server, Latest stable version 3.141.59
and
Python 3.141.0 November 01, 2018 4.0.0a6.post1 May 28, 2020 Download (I am not using Python but I might in the future.)

Then I opened Excel VBA and opened Tools but could not find the “Selenium Type Library” option in the drop down.

I did more reading and I downloaded SeleniumBasic at https://github.com/florentbr/SeleniumBasic/releases/tag/v2.0.9.0

This made the option “Selenium Type Library” appear on the Tools dropdown.

I selected the “Selenium Type Library” option.

I entered this code in the VBA editor, which I got off the web. It opens Chrome. I could not find how to open Edge.

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

It failed on the line:

driver.Start "Chrome"

It gave an error:

Exception from unknown error

6 Answers 6

4

Do you have the selenium chromium driver installed? That is required and it is different than the server and Visual library. This is the actual chrome binary that will launch and run. Download the latest version and place it in path such that basic can access it. I believe the path is C:\Users\ *Username\AppData\Local\SeleniumBasic

The executable should also be lowercase:

Dim driver As New WebDriver 
driver.Start "chrome" 
driver.Get "https://duckduckgo.com" 
Sign up to request clarification or add additional context in comments.

3 Comments

Yes, I have the "chromedriver.exe" installed in C:\Users\myUsername\AppData\Local\SeleniumBasic. Also, In the code line: "driver.Start "Chrome" I changed "Chrome" to "chrome" (all lower case) and it still bombs-out on that line of code.
Have you deleted the default chromedriver.exe and download the latest copy?
That was it! I replaced the old chromedriver.exe with the latest driver and, eureka! it worked!
0

don't forget to add the VBA reference: Selenium Type Library

here is a link that had all the puzzle pieces in one place: https://www.makeuseof.com/tag/how-to-automate-firefox-or-chrome-with-vba-and-selenium/

2 Comments

While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
0

The OP did say - to automate the Edge browser (or any other browser) via Excel VBA - and technically nowadays IE is available via Edge in IE mode.

This code works on Windows 11 with Excel 365 VBA.

Sub sbIETest()
      Dim ie As New InternetExplorer ' ref - Microsoft Internet Controls
      ie.Visible = True
      ie.navigate "https://www.microsoft.com/en-gb/download/internet-explorer.aspx"
      Do
        DoEvents
      Loop Until ie.readyState = READYSTATE_COMPLETE
End Sub

Comments

0

For Edge -

Check edgedriver.exe version from the command line -

PS C:\Users\david\appdata\Local\SeleniumBasic> .\edgedriver -v

Microsoft Edge WebDriver 116.0.1938.81 (bc0eb28b55bd3...

download the latest edgedriver version -

from here https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/

this code was tested on Windows 11 with Excel 365 VBA

Option Explicit

Sub sbBing()
    Dim wd As New WebDriver
    wd.Start "edge", "https://www.bing.com" 
    wd.Get "/" 
    sbDelay (200000) 
End Sub


Sub sbDelay(delay As Long) 
    Dim i As Long 
    For i = 1 To delay 
        DoEvents 
    Next i 
End Sub

Comments

0

You can download and call Edge (or any other) Driver directly like:

Set shell = CreateObject("WScript.Shell")
shell.Run "c:\download\msedgedriver.exe --port=9515", 0, False

' Wait for the driver to be available
If Not WaitForDriver("http://localhost:9515/status", 5000) Then
    MsgBox "Error: msedgedriver did not respond."
    WScript.Quit
End If

' Create session
sessionJson = "{""capabilities"": {""alwaysMatch"": {""browserName"": ""MicrosoftEdge""}}}"
sessionResponse = SendRequest("http://localhost:9515/session", "POST", sessionJson)
sessionId = ParseJson(sessionResponse).value.sessionId

' Navigate to Google
navJson = "{""url"":""https://www.google.com""}"
SendRequest "http://localhost:9515/session/" & sessionId & "/url", "POST", navJson

' Execute JavaScript
scriptJson = "{""script"":""return document.title;"",""args"":[]}"
jsResult = SendRequest("http://localhost:9515/session/" & sessionId & "/execute/sync", "POST", scriptJson)
MsgBox ParseJson(jsResult).value

' End session
SendRequest "http://localhost:9515/session/" & sessionId, "DELETE", ""

Function ParseJson(jsonText)
    Dim html, jsonObj

    Set html = CreateObject("htmlfile")
    html.Write "<script>document.write('')</script>"
    html.Close

    Set jsonObj = html.parentWindow.eval("(" & jsonText & ")")

    Set ParseJson = jsonObj
End Function

Function WaitForDriver(url, timeout)
    Set http = CreateObject("MSXML2.XMLHTTP")
    startTime = Timer
    Do
        On Error Resume Next
        http.Open "GET", url, False
        http.Send
        If http.Status = 200 Then
            WaitForDriver = True
            Exit Function
        End If
        On Error GoTo 0
        WScript.Sleep 500
    Loop While (Timer - startTime) < (timeout / 1000)
    WaitForDriver = False
End Function

Function SendRequest(url, method, body)
    Set http = CreateObject("MSXML2.XMLHTTP")
    http.Open method, url, False
    http.setRequestHeader "Content-Type", "application/json"
    http.Send body
    SendRequest = http.ResponseText
End Function

You can download the Edge Driver here:
https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver

There is one problem is that the diver and the Browser versions tend to get out of synch. You can use this script to to keep web driver up to date.

Set fso = CreateObject("Scripting.FileSystemObject")
DownloadLatestSelenium 
WScript.Echo "Done"

'==========================================
Sub DownloadLatestSelenium()
    Dim oShell: Set oShell = WScript.CreateObject("WSCript.shell")
    Dim oHttp: Set oHttp = CreateObject("MSXML2.ServerXMLHTTP.6.0") 
    oHttp.Open "GET", "https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver", False
    oHttp.Send
    Dim s: s = oHttp.responseText
    Dim iPos: iPos = InStr(1, s,"Stable Channel")
    iPos = InStr(iPos, s,"/edgedriver_win64.zip""")
    s = Mid(s, iPos - 50, 100)
    iPos = InStr(1, lcase(s),"https://")
    s = Mid(s, iPos)
    iPos = InStr(1, s, """")
    Dim sUrl: sUrl = Mid(s, 1, iPos - 1)

    Dim sFolder: sFolder = GetBaseFolder()
    Dim sFilePath: sFilePath = sFolder & "\edgedriver_win64.zip"

    If fso.FileExists(sFilePath) Then
      fso.DeleteFile sFilePath, True
    End If

    DownloadFile sUrl, sFilePath
    'WScript.Echo "Downloaded " & sFilePath

    Dim sEdgeDriverPath: sEdgeDriverPath = sFolder & "\msmsedgedriver.exe"
    If fso.FileExists(sEdgeDriverPath) Then
      fso.DeleteFile sEdgeDriverPath, True
    End If

    UnzipFile sFilePath, sFolder

    If fso.FileExists(sEdgeDriverPath) = False Then
      WScript.Echo "File could not be unzipped"
      Exit Sub
    End If

    Dim sSeleniumVersion: sSeleniumVersion = GetMajorVersion(fso.GetFileVersion(sEdgeDriverPath))
    'WScript.Echo "Downloaded Version: " & sSeleniumVersion

    Dim sDestFilePath: sDestFilePath = "c:\download\msedgedriver.exe"
    Dim sDestSeleniumVersion: sDestSeleniumVersion = GetMajorVersion(fso.GetFileVersion(sDestFilePath))

    If sDestSeleniumVersion = sSeleniumVersion Then
        WScript.Echo "No Action Needed. Quitting. Versions are is the same " & sSeleniumVersion & vbCrLf & sEdgeDriverPath & vbCrLf & sDestFilePath 
        Exit Sub
    Else
        If fso.FileExists(sDestFilePath) Then
            fso.DeleteFile sDestFilePath, True
            fso.CopyFile sEdgeDriverPath, sDestFilePath
            WScript.Echo "Downloaded Version: " & sSeleniumVersion & " <> Dest Version " & sDestSeleniumVersion & " Updated: " & sDestFilePath 
        End If
    End If

    sDestFilePath = "c:\download\edgedriver_" & sSeleniumVersion & ".exe"
    If fso.FileExists(sDestFilePath) = False Then
      fso.CopyFile sEdgeDriverPath, sDestFilePath
        WScript.Echo " Updated: " & sDestFilePath 
    End If
End Sub

Sub UnzipFile(zipPath, destFolder)
    Dim winrarPath, shell, cmd, archiveName
    winrarPath = "C:\Program Files\WinRAR\WinRAR.exe" 

    If fso.FileExists(winrarPath) Then
        ' Use WinRAR to extract the zip
        cmd = Chr(34) & winrarPath & Chr(34) & " x -o+ -ibck " & Chr(34) & zipPath & Chr(34) & " " & Chr(34) & destFolder & Chr(34)
        Set shell = CreateObject("WScript.Shell")
        shell.Run cmd, 0, True
    Else
        ' Use Shell.Application to extract
        Set shell = CreateObject("Shell.Application")
        Dim source, destination, items
        Set source = shell.NameSpace(zipPath)
        Set destination = shell.NameSpace(destFolder)

        If Not source Is Nothing And Not destination Is Nothing Then
            ' 20 = 16 (Yes to All) + 4 (No UI)
            destination.CopyHere source.Items, 20
            Wscript.Sleep 1000
        Else
            WScript.Echo "Error: Invalid zip file or destination."
        End If
    End If

    Set shell = Nothing
End Sub


Sub DownloadFile(sUrl, sFilePath)
  Dim oHTTP: Set oHTTP = CreateObject("Microsoft.XMLHTTP")
  oHTTP.Open "GET", sUrl, False
  oHTTP.Send

  If oHTTP.Status = 200 Then 
    Set oStream = CreateObject("ADODB.Stream") 
    oStream.Open 
    oStream.Type = 1 
    oStream.Write oHTTP.ResponseBody 
    oStream.SaveToFile sFilePath, 2 
    oStream.Close 
  Else
    WScript.Echo "Error Status: " & oHTTP.Status & ", URL:" & sUrl
  End If
End Sub

Function GetBaseFolder()
  Set oFile = fso.GetFile(WScript.ScriptFullName)
  GetBaseFolder = oFile.ParentFolder
End Function

Function GetMajorVersion(s)
  i = InStr(s,".")
  If i <> 0 Then
    GetMajorVersion = Mid(s, 1,i - 1)
  Else
    GetMajorVersion = s
  End If
End Function

Comments

-1

For Edge you don't need Selenium. Use "Microsoft Internet Controls" instead of "Selenium Type Libra"

    Sub test()

      Dim ie As New InternetExplorer
      Dim doc As New HTMLDocument
      Dim ecoll As Object
      ie.Visible = True
      ie.navigate "YOUR_URL"
      Do
        DoEvents
      Loop Until ie.readyState = READYSTATE_COMPLETE

    End Sub

1 Comment

This is not Edge. This is IE (Internet Explorer) But see: microsoft.com/en-us/download/internet-explorer.aspx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.