How to run Selenium java/html script uing Excel VBA? - vba

I have recorded some actions where the user will navigate to a webpage and perform some tasks using Selenium IDE on Firefox. Now i wish to export this test case using Java or HTML.
I was wondering if this script can be executed using Excel VBA on a command button click?
I have opened the Firefox browser and as of now i have come up only with this much:
Private Sub CommandButton26_Click()
Dim objShell
Set objShell = CreateObject("WScript.Shell")
objShell.Run ("""C:\Program Files (x86)\Mozilla Firefox\Firefox.exe""")
Set objShell = Nothing
End Sub

Related

How do I programmatically print an item in VBA without any dialogues or user-interfaces? (VBA)

Windows 10
Microsoft 365
Outlook v.2205
I am writing a macro that prints the selected email AND attachments to PDF. I need this to be fully automatic, without any user intervention once the macro starts. The problem I have, is that when the mailItem.PrintOut command is used, a print dialogue window appears and freezes the macro until the user advances the window manually.
I am able to cobble together the body of the email using the Word object library where I can easily print, but for email attachments (such as PDFs) I am at a loss.
I have scoured the web looking for a solution to this. I have found nothing so far that can be done in pure native VBA.
Image of the printer dialogue that I would like to bypass:
I previously asked here whether it is possible to manipulate the printer dialogue window using API/VBA code, but later realized that once the printer dialogue appears, VBA stops working so I must find a way to bypass the dialogue window altogether.
It seems unlikely to me that there does not exist a way to do this.
Code posted below (simplified for reference):
Private Sub printEmail()
Dim mySelection As Outlook.Selection
Dim myEmail As MailItem
Set mySelection = Application.ActiveExplorer.Selection
' If item = mailitem, print
If mySelection.Item(1).Class = 43 Then
Set myEmail = mySelection.Item(1)
myEmail.PrintOut ' <===###this command causes a dialogue to appear###
' Else, exit sub
Else
MsgBox "Select a mail item"
Exit Sub
End If
End Sub
You need to save attached files (for example, PDF) on the disk and then use a shell command to print the saved file. Or if you have got Acrobat Reader installed on the system you could use something like that:
Dim oShell As Object, oExec As Object
Set oShell = CreateObject("Wscript.Shell")
Set oExec = oShell.exec("""" & "C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe" _
& """/p /h """ & SomePath & "\" & "invoice.pdf" & """")
DoEvents
oExec.Terminate
Set oExec = Nothing
Set oShell = Nothing

Selenium VBA: Fill a Windows Popup to upload a file

I'm not able to have interaction with Windows PopUp to write a dedicated path to upload a file in VBA using Selenium due to Chrome browser.
I have found some solutions in Python but nothing in VBA. This is why I have tried to convert the code in VBA but without success.
Find below an example code:
Sub Fullfil_Windows_PopUp()
Dim driver
Dim elem
Set Waiter = CreateObject("Selenium.Waiter")
Set Assert = CreateObject("Selenium.Assert")
Set driver = CreateObject("Selenium.ChromeDriver")
'open the browser and the page
driver.Get "https://fr.imgbb.com/"
While Waiter.Not(InStr(driver.Title, "ImgBB — Upload Image — Hébergement d'images gratuit")): Wend
'open upload window
Set elem = driver.FindElementsByXPath("//*[#id='home-cover-content']/div[2]/a").Item(1)
elem.Click
'Trial 1
driver.SwitchToWindowByTitle "Ouvrir" '--> NOK (error window not found)
driver.SendKeys "D:\Test.jpg"
'Trial 2
driver.SwitchToAlert.SendKeys "D:\Test.jpg" '--> NOK (error No Alert present)
'Trial 3
Set wsh = CreateObject("WScript.Shell")
wsh.SendKeys "D:\Test.jpg" '--> NOK (no action)
End Sub
Thanks in advance for your suggestions
I have used a "back door" to fill the file name into the filemanager window.
As the cursor is already into the filename field of the window, I have created an external script in VBS to write the file name (and 2x TAB + ENTER to validate the window).
Below the code of the VBS file:
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.SendKeys "D:\Test.jpg"
WshShell.SendKeys "{TAB}"
WshShell.SendKeys "{TAB}"
WshShell.SendKeys "{ENTER}"
And I execute this script after to have open the filemanager window with selenium:
Sub Fullfil_Windows_PopUp()
Dim driver
Dim elem
' Chrome browser
Set driver = CreateObject("Selenium.ChromeDriver")
'open the browser and the page
driver.Get "https://fr.imgbb.com/"
Sleep 1000
' Open upload window
Set elem = driver.FindElementsByXPath("//*[#id='home-cover-content']/div[2]/a").Item(1)
elem.Click
' Write the filename with VBS script
Set oWsh = CreateObject("Shell.Application")
oWsh.ShellExecute "D:\filename.vbs"
Set oWsh = Nothing
Sleep 1500
End Sub
But I continue to search a solution directly with Selenium because for example, the filename is directly indicated into the VBS File and this is not easy to use it like a variant.
#Armin's answer works quite well if you are in a similar quandary. I don't know of any other method at present to interact with a file window at upload point.
For more details, a VBS file is a Microsoft VB-Script file. You can create this using Notepad, putting in the code, save as, change file name, include ".vbs" extension and change file type to all files.
If you use the code in the answer as it is, you're likely to be greeted with an unfriendly "Undefined Variable" error so you should declare the variable first as an object:
Dim oWsh as Object
Depending on your code, you may also be greeted with an error for the "Sleep*" command used. You can change this to using an implicit or explicit "Wait" as needed:
driver.Wait 1500
Cheers!

Fill proxy form when PC is locked

I need to enter a site for which a proxy form has to be filled. I couldn't get through the form using Selenium VBA.
I called a VBS script from VBA to fill the form. It works when the PC is not locked.
Below is the proxy form.
Outlook VBA code to call VBS:
Dim bot as new chromedriver
bot.Start "chrome", "https://nissan.service-now.com/nav_to.do?uri=%2Fhome.do%3F"
bot.Get ("https://nissan.service-now.com/nav_to.do?uri=%2Fhome.do%3F") '//load webpage
strFileName = "d:\LocalData\Z018439\Desktop\MY\NX-AMO\VBACodes\Shell.vbs"
Set oshell = CreateObject("Wscript.shell")
oshell.Run "vbsc " & strFileName '//call vbs file
VBS code to fill proxy form:
Sub test()
Dim shell_object
Dim app_path, time
wscript.Sleep 12000
shell_object = "wscript.shell"
Set objshell = CreateObject(shell_object)
objshell.SendKeys ""
objshell.SendKeys "{Tab}"
objshell.SendKeys ""
objshell.SendKeys "{Enter}"
End Sub
When the PC is locked, keyboard function is disabled and hence sendkeys(VBS) is not working. Launch is done upon arrival of a new mail in Outlook.
How do I fill the proxy form when the PC is locked.

VBA Automation - Downloading a file using IE 11 (64bit)

This question seems to have been asked dosens of times, however none of the solutions I have found seem to be able to solve my problem.
As the webpage is using a certificate token I am forced to log on to the webpage manually before I can activate the VBA script, which is no problem. An important note is that the link to the report is dynamic and therefore I cannot link directly to the report itself and therefore I have to navigate the webpage with my Script. Below you find the script i am using to locate the window I have logged on to the webpage with:
Sub WebPageOpen()
Dim HTMLDoc As HTMLDocument
Dim oHTML_Element As IHTMLElement
On Error GoTo Err_Clear
Set objShell = CreateObject("Shell.Application")
IE_count = objShell.Windows.Count
For X = 0 To (IE_count - 1)
On Error Resume Next ' sometimes more web pages are counted than are open
my_url = objShell.Windows(X).document.Location
my_title = objShell.Windows(X).document.Title
If my_title Like "MY Webpage name" Then 'compare to find if the desired web page is already open
Set IE = objShell.Windows(X)
marker = 1
Exit For
Else
End If
Next
If marker = 0 Then
MsgBox ("Webpage is not open - Please log on to webpage")
Exit Sub
Else
End If
Do
' Wait till the Browser is loaded
Loop Until IE.readyState = READYSTATE_COMPLETE
' I have removed all my navigation commands here,as it would just be bloating the query. It clicks the link and the Save/open ribbon appears in IE.
End sub
Can anyone help me with some sort of solution to how I can interact with the Open/Save as ribbon which appears when I download the file?
That ribbon is called Notification bar.
You can use Alt+N to focus on the Notification Bar. And then send {tab} key to navigate to the specific button.
With VBA, you may use Autohotkey.dll or AutoItX3.dll to send these hotkey combinations.
Add reference to AutoItX3.dll (for both 32-bit and 64-bit OS)
Append the following
set X=CreateObject("AutoItX3.Control")
X.send !N{tab}{down 2}{enter} 'This is for Save-as

Copying Selected Information from Internet Explorer

I've created a IE based VBA script in Excel using. The VBA script opens up IE, navigates to a web site, logs in to the site, enters in search criteria and opens a new window. I used the function GetIE to mirror that new windows website back to the original instance of IE so the VBA script can stay focused on the original instance. It then clicks a link on that window and then highlights some pricing information. But that's where I'm stuck. I desperately need code that will simply copy what i've highlighted to my clipboard. Here is the code posted:
Sub ExtractPMDPricing()
Dim core As ICore
Set core = New OpenTwebstLib.core
Dim IE As InternetExlorer
Set IE = CreateObject("Internet Explorer")
Dim browser As IBrowser
Set browser = core.StartBrowser("xxxxxxxxxxxxxxxx")
Range("A1").Select
Selection.Copy
Call browser.FindElement("div", "id=footer-position-placeholder").Click
Call browser.FindElement("a", "uiname=log in, index=1").Click
Call browser.FindElement("input text", "id=erznr").InputText(ActiveCell.Value)
Call browser.FindElement("td", "index=2").Click
Call browser.FindElement("input button", "id=sub").Click
Application.Wait (Now + #12:00:06 AM#)
Call GetIE
Call browser.FindElement("span", "id=selectionctrl_MATCONTSMALLCTRL_navigatorctrl_treeselectionctrl_MATCONTSMALLCTRL_navigatorctrl_Prices-cnt-start").Click
Call browser.FindElement("input text", "id=selectionctrl_MATCONTSMALLCTRL_subcatviewerctrl_selectionctrl_mod_ergebnis_ga[1].kbetr").RightClick
txt = IE.document.parentWindow.clipboardData.GetData("TEXT")
Range("B2").Select
ActiveCell.PasteSpecial
End Sub
' ZVI:2011-05-30 VBA Macro For Already Open IE Window
' Reference required: Tools - References - Microsoft Internet Controls
Function GetIE()
Dim shellWins As ShellWindows
Dim IE As InternetExplorer
Set shellWins = New ShellWindows
If shellWins.Count > 0 Then
' Get IE
Set IE = shellWins.Item(0)
Else
' Create IE
Set IE = New InternetExplorer
IE.Visible = False
End If
IE.Navigate "xxxxxxxxxxxxxxxx"
Set IE = Nothing
Set shellWins = Nothing
End Function
The copy code I need should fit in right below the last Call browser.findelement line before the end of the sub above Range ("B2").
txt=ie.document.parentwindow.clipboardData.GetData("TEXT")
this gets clipboard. Use Setdata.
Also you can give browser commands.
Executes a command on an OLE object and returns the status of the command execution using the IOleCommandTarget interface. (ie in basic ie.execwb 5, 0)
Syntax
object.ExecWB( _
cmdID As OLECMDID, _
cmdexecopt As OLECMDEXECOPT, _
[pvaIn As Variant,] _
[pvaOut As Variant])
Parameters
cmdID
Long that represents the identifier of the command to execute. For more information on command identifiers, see MSHTML Command Identifiers.
cmdexecopt
OLECMDEXECOPT value that specifies the command options.
pvaIn
Optional. A Variant used for specifying command input arguments.
pvaOut
Optional. A Variant used for specifying command output arguments.
IDM_COPY Command ID
--------------------------------------------------------------------------------
Copies the current selection to the clipboard.
C++ Information
Command group CGID_MSHTML (defined in mshtmhst.h)
Symbolic constant IDM_COPY
User interface None. Set nCmdExecOpt to OLECMDEXECOPT_DONTPROMPTUSER.
IOleCommandTarget::Exec parameters pvaIn Set to NULL.
pvaOut Set to NULL.
Header file mshtmcid.h
Applies to IHTMLDocument2::execCommand, IHTMLDocument2::queryCommandEnabled, IHTMLDocument2::queryCommandIndeterm, IHTMLDocument2::queryCommandState, IHTMLDocument2::queryCommandSupported, IHTMLDocument2::queryCommandValue, IOleCommandTarget::Exec, IOleCommandTarget::QueryStatus.
Minimum Availability
Internet Explorer 4.0 and later.