8

I am having problems even setting up Selenium for VBA. I have been reading online on what to do, download the selenium (https://github.com/florentbr/SeleniumBasic/releases/tag/v2.0.9.0) add extension and etc. However, I am still struggling to get it to work.

Even writing a simple code like the following which I have found online:

Public Sub Demo()
    Dim d As WebDriver
    Set d = New ChromeDriver
    Const URL = "https://www.google.com/"

    With d
        .Start "Chrome"
        .get URL
        .FindElementById("lst-ib").SendKeys "Selenium basic GitHub"
         .FindElementsByTag("form")(1).FindElementByCss("input[value='Google Search']").Click
        '.Quit
    End With
End Sub

Gives me an Automation error.

I would like to use google chrome in the same way as internet explorer. I would appreciate any help with setting up selenium , and I know my question can be seen as silly.

10
  • 1
    Did you Check the Reference Selenium Type Library ? If not select the Reference in Tools>References Commented Jul 26, 2019 at 9:11
  • I did add the reference Selenium Type Library but for some reason it still gives me the automation error Commented Jul 26, 2019 at 9:17
  • Which line shows the error ? Commented Jul 26, 2019 at 9:17
  • Set d = New ChromeDriver And the automation error that it gives me is : Run time error : '-2146232576 Commented Jul 26, 2019 at 9:22
  • 1
    Do you have the right chromedriver.exe for your version of chrome and is that driver in the selenium folder? Commented Jul 26, 2019 at 11:06

5 Answers 5

26

First of all, go to control panel and uninstall previous installation of selenium and then follow the steps 1- Download the latest version of chrome and make sure of the version of Chrome from Help >> About Google Chrome. You would see something like that Version 75.0.3770.142 (Official Build) (32-bit)

2- Download the latest version from the LINK

3- Download the chromedriver from the follwoing LINK Make sure of the version that suits your chrome version As for the Google Chrome version I posted the most suitable version of chromedriver is ChromeDriver 75.0.3770.140

  1. Now setup SeleniumBasic >> After setup unzip the chromedriver file chromedriver_win32.zip and copy the chromedriver.exe to the path of selenium Here's two possibilties: First >> C:\Program Files\SeleniumBasic Second >> C:\Users\%username%\AppData\Local\SeleniumBasic Copy the chromedriver.exe to the SeleniumBasic path

  2. Open new blank excel file >> Press Alt + F11 (Visual Basic Editor) >> Tools >> References >> Selenium Type Library

  3. Insert new module and paste the following code to test

Sub Test()
    Dim bot         As New WebDriver
    
    bot.Start "chrome", "https://www.google.com"
    bot.Get "/"
    Stop
End Sub

Sign up to request clarification or add additional context in comments.

13 Comments

Followed the steps, still continues to give the exact same error, Tomorrow I will try to find a different computer and try on it to see if it gives a different result.
YasserKhalil, you are the king of selenium, Reinstalled my net framework and it is working now, Huge thanks for the help, for the quick response and the fact that for the past week you kept checking on here and help me out, huge huge thanks
Now just left to learn how to navigate with selenium in the same way as I do in internet explorer
You are a legend, works, thank you very much for this answer, Yasser!
@YasserKhalil I got 3.5 as well but I think you are right about the problem being in the framework. I have apparently an issue with the NET framework. Most of the time, my Excel crashes when opening a file with PowerQuery. It crashes on "Loading .Net Framework". When I do manage to open such a file, I succeed in running the function too.
|
2

I downgraded chrome.exe to one version lower downloads (off the selenium chrome webdriver site) in Users/?/AppData/Local/SeleniumBasic directory and it worked. ..running windows 10.

Comments

0

Check your chromedriver version from the command line -

PS C:\Users\david\appdata\Local\SeleniumBasic> .\chromeDriver -v ChromeDriver 118.0.5993.70 (e52f33f30b91b4ddfad...

Download chromedriver version from here -

https://googlechromelabs.github.io/chrome-for-testing/#stable

This code works on Windows 11 with Excel 365 VBA -

Sub sbChromeDriver() 
    Dim bt As New Selenium.ChromeDriver 
    bt.Start 
    bt.Get "https://www.google.com" 
    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

To resolve the "Automation error" when using the Selenium library in VBA Excel, follow these combined steps:

1. Download and Install Microsoft .NET Framework 3.5: SeleniumBasic may requires components from Microsoft .NET Framework 3.5. Download and install it from the official Microsoft website: Microsoft .NET Framework 3.5 Download

2. Enable Selenium in VBA References: Ensure Selenium is enabled in your VBA project:

Open the VBA editor (press Alt + F11 in Excel or other Office applications). Go to Tools > References. Check the box for Selenium Type Library. If it is missing, reinstall SeleniumBasic.

3. Ensure ChromeDriver and Chrome Browser Match Versions The ChromeDriver version must match your installed Google Chrome version:

Check your Chrome version by navigating to chrome://settings/help in your browser. Download the matching ChromeDriver version from the official site: ChromeDriver Downloads. => Choose Binary: chromedriver

4. Replace ChromeDriver in SeleniumBasic Folder Once you have the correct ChromeDriver version:

Locate the SeleniumBasic installation folder. Replace the existing chromedriver.exe file in this folder with the newly downloaded one.

Summary of Steps:

Install Microsoft .NET Framework 3.5.

Enable Selenium Type Library in VBA references.

Download ChromeDriver and ensure ChromeDriver matches your Chrome browser version.

Copy the updated ChromeDriver to the SeleniumBasic installation folder.

Comments

0

If you use VBA there is no need to install Selenium Basic. You can download and call Edge Driver directly like:

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

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

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.