How can I set a value of a ComboBox on a website? - excel

I've been trying to write some code that logs in into a website, while I can set the values of "login" or "password", I can't set the value of the "empresa" field, as it is a combobox.
the login page is in the image on this link: https://i.stack.imgur.com/3bk6B.png
When i Inspect object on the website, the "Empresa" field gives me this:
<div id="cmbProject_cmb" class="RadComboBox RadComboBox_" style="border-style:None;font-size:18px;width:100%;white-space:normal;background-color:transparent;">
<table summary="combobox" style="border-width:0;border-collapse:collapse;width:100%" class="rcbFocused">
<tbody><tr class="rcbReadOnly">
<td class="rcbInputCell rcbInputCellLeft" style="width:100%;"><input name="cmbProject$cmb" type="text" class="rcbInput radPreventDecorate" id="cmbProject_cmb_Input" value="Empresa" readonly="readonly" style="color:Black;font-size:18px;" autocomplete="off"></td><td class="rcbArrowCell rcbArrowCellRight"><a id="cmbProject_cmb_Arrow" style="overflow: hidden;display: block;position: relative;outline: none;">select</a></td>
</tr>
</tbody></table><input id="cmbProject_cmb_ClientState" name="cmbProject_cmb_ClientState" type="hidden" autocomplete="off" value="{"logEntries":[],"value":"WTM - PROD|1","text":"WTM - PROD","enabled":true,"checkedIndices":[],"checkedItemsTextOverflows":false}">
</div>
The code i've been using is as follows
Dim HTMLDoc As HTMLDocument
Dim oBrowser As InternetExplorer
Sub Login()
Dim oHTML_Element As IHTMLElement
Dim sURL As String
On Error GoTo Err_Clear
sURL = "https://prodweb-votorantim.mc1.com.br/WTM/aspx/Login.aspx"
Set oBrowser = New InternetExplorer
oBrowser.Silent = True
oBrowser.timeout = 60
oBrowser.navigate sURL
oBrowser.Visible = True
Do
Loop Until oBrowser.readyState = READYSTATE_COMPLETE
Set HTMLDoc = oBrowser.document
HTMLDoc.all.txtUserName_txt.Value = "login"
HTMLDoc.all.txtPassword_txtPass.Value = "password"
HTMLDoc.all.cmbProject.Value = "WTM - PROD"
For Each oHTML_Element In HTMLDoc.getElementsByTagName("input")
If oHTML_Element.Type = "submit" Then oHTML_Element.Click: Exit For
Next
Err_Clear:
Resume Next
End Sub

You can use javascript to set value
Option Explicit
'VBE > Tools > References: Microsoft Internet Controls
Public Sub Login()
Dim ie As New InternetExplorer
With ie
.Visible = True
.Navigate2 "https://prodweb-votorantim.mc1.com.br/WTM/aspx/Login.aspx"
While .Busy Or .readyState < 4: DoEvents: Wend
With .document
.querySelector("#txtUserName_txt").Value = "bob.builder#web.net"
.querySelector("#txtPassword_txtPass").Value = "topSecret"
.parentWindow.execScript "document.querySelector('#cmbProject_cmb_Input').value = 'WTM-PROD';"
.querySelector("#btnLogin_input").Click
End With
Stop ' <delete me later
.Quit
End With
End Sub

Related

Inspect element in chrome doesnt show any id for the box on the website, how do i find that? code included [duplicate]

I'm very fresh to excel VBA. I tried use all potential solutions in the internet for activate selectitem in web and get data table but it didn't work. My Excel VBA code and Javascript is below.
Sub GetQuarterFinancials()
Dim ie As Object, URL As String
URL = "https://www.marketwatch.com/investing/stock/aapl/financials"
Set ie = CreateObject("internetexplorer.application")
With ie
.Visible = True
.navigate URL
Do While .Busy
DoEvents
Loop
Do While .readyState <> 4
DoEvents
Loop
Set ticker = ie.document.getElementById("autocomplete_input")
ticker.value = "FB"
.document.getElementById("investing_ac_button").Click
Application.Wait (Now + TimeValue("00:00:05"))
Set selectitem = ie.document.getElementsByTagName("select")
For Each i In selectitem
i.value = "/investing/stock/msci/financials/income/quarter"
i.FireEvent ("onchange")
Next i
End With
End Sub
<select style="float:right" onchange="window.location = this.options[selectedIndex].value;">
<option value="/investing/stock/msci/financials" selected="selected">Annual Financials</option>
<option value="/investing/stock/msci/financials/income/quarter" >Quarter Financials</option>
</select>
<div style="clear:both"></div>
</div>
<div class="block">
<h2>Annual Financials for MSCI Inc.</h2>
You can use a css attribute = value selector to target the appropriate option from dropdown then select it.
Option Explicit
'VBE > Tools > References:
' Microsoft Internet Controls
Public Sub MakeSelections()
Dim ie As New InternetExplorer
With ie
.Visible = True
.Navigate2 "https://www.marketwatch.com/investing/stock/aapl/financials"
While .Busy Or .readyState < 4: DoEvents: Wend
With .document
.querySelector("#autocomplete_input").Value = "FB" 'you could avoid search by adding ticker into url
.querySelector("#investing_ac_button").Click
End With
While .Busy Or .readyState < 4: DoEvents: Wend
Dim ele As Object
With .document
Do
On Error GoTo 0
Set ele = .querySelector("[value^='/investing/stock/fb/financials/income/quarter']")
On Error Resume Next
Loop While ele Is Nothing
.querySelector("[value^='/investing/stock/fb/financials/income/quarter']").Selected = True
.querySelector(".financials select").FireEvent "onchange"
Stop 'delete me later
End With
.Quit
End With
End Sub

Excel VBA .click event not working with <a> tag

I'm trying to automate logging into a website to get my account balance.
The .click event on the login button is not working. I feel I'm missing something simple.
Sub test()
Set IE = CreateObject("InternetExplorer.Application")
my_url = "https://www.synchronycredit.com/eSecurity/Login/login.action?clientId=google&accountType=plcc&langId=en"
With IE
.Visible = True
.navigate my_url
.Top = 50
.Left = 530
.Height = 400
.Width = 400
Do Until Not IE.Busy And IE.readyState = 4
DoEvents
Loop
End With
IE.document.getElementById("loginUserID").Value = "userNameHere"
IE.document.getElementById("loginPassword").Value = "passWordHere"
IE.document.getElementByID("secLoginBtn").Click
Do Until Not IE.Busy And IE.readyState = 4
DoEvents
Loop
End Sub
Here is the code from the website:
<a tabindex="0" title="Login to your account" id="secLoginBtn" role="button" style="cursor: pointer;" data-reason="login:start:submit" onclick="javascript:setRememberMeFlag('rememUID');" data-type="button" class="ADAbtn btn secLoginBtn secureLockImg ensightenmEvent">
<img class="pull-left" src="/essimages/cs/groups/ess_webasset/generic/#common/en/brandimages/044828.png" alt="">
Secure Login</a>
First of all:
Always use Option Explicit as first line in every VBA module.
To solve your problem you need first to trigger the keypress events for the input fields. After entering the values you can click the submit button.
First line:
Option Explicit
Main makro:
Sub test()
Dim browser As Object
Dim url As String
Dim nodeUserName As Object
Dim nodePassWord As Object
Dim nodeSubmitButton As Object
Dim domDoc As Object
Dim userName As String
Dim passWord As String
userName = "Your Name"
passWord = "YourPassword"
Set browser = CreateObject("InternetExplorer.Application")
url = "https://www.synchronycredit.com/eSecurity/Login/login.action?clientId=google&accountType=plcc&langId=en"
'Initialize Internet Explorer, set visibility,
'call URL and wait until page is fully loaded
Set browser = CreateObject("internetexplorer.application")
browser.Visible = True
browser.navigate url
browser.Top = 50
browser.Left = 530
browser.Height = 400
browser.Width = 400
Do Until browser.readyState = 4: DoEvents: Loop
Set domDoc = browser.document
Set nodeUserName = domDoc.getElementByID("loginUserID")
Call TriggerEvent(domDoc, nodeUserName, "onKeypress")
nodeUserName.Value = userName
Set nodePassWord = domDoc.getElementByID("loginPassword")
Call TriggerEvent(domDoc, nodePassWord, "onKeypress")
nodePassWord.Value = passWord
Set nodeSubmitButton = domDoc.getElementByID("secLoginBtn")
nodeSubmitButton.Click
End Sub
Subroutine to trigger a html event:
Private Sub TriggerEvent(htmlDocument As Object, htmlElementWithEvent As Object, eventType As String)
Dim theEvent As Object
htmlElementWithEvent.Focus
Set theEvent = htmlDocument.createEvent("HTMLEvents")
theEvent.initEvent eventType, True, False
htmlElementWithEvent.dispatchEvent theEvent
End Sub

VBA Internet explorer script only works 50% of the time

I have a script on VBA that loads up a site, copies data & pastes it on a hidden page. It has worked before but I have to run it about 20 times to get it to do what I want it to do. The errors are very inconsistent and I am debating if I should proceed with this as I need at least a 95% success rate.
Majority of the time the data is not copied correctly & the page is blank, the script finishes with out error but nothing happens.
The other time the script fails is on Set ieTable = ieDoc.all.item -- Do While ieApp.Busy: DoEvents: Loop -- Set ieDoc = ieApp.Document
As you can see, just to be able to check where the errors are occurring I have plagued everything with message prompts.
Sub Pull_Data()
'Kills ALL IE windows
On Error GoTo Ignore:
Call IE_Sledgehammer
Ignore:
Dim ieApp As InternetExplorer
Dim ieDoc As Object
Dim ieTable As Object
Dim clip As DataObject
Dim UserName As String, Password As String
Dim SubmitButton
Dim i As Integer
'Create anew instance of ie
Set ieApp = New InternetExplorer
ieApp.Navigate "Intranet site I cannot share"
'Debugging
ieApp.Visible = True
'When busy - wait
On Error GoTo Skip_wait
Do While ieApp.Busy: DoEvents: Loop
Do Until ieApp.ReadyState = READYSTATE_COMPLETE: DoEvents: Loop
GoTo Login
'Debugging
Skip_wait:
MsgBox ("You skipped the first wait")
Login:
'*****common error*****
Set ieDoc = ieApp.Document
Set SubmitButton = ieDoc.getElementsByTagName("input")
'Login script
With ieDoc.forms(0)
If Err.Number = 424 Then
GoTo skip_login
.UserName.Value = "USERNAME"
.Password.Value = "PASSWORD"
SubmitButton(i).Click
End If
End With
GoTo wait
'Debugging
skip_login:
MsgBox ("You skipped the login")
'When busy - wait
wait:
On Error GoTo Skip_waiting
Do While ieApp.Busy: DoEvents: Loop
Do Until ieApp.ReadyState = READYSTATE_COMPLETE: DoEvents: Loop
GoTo Copypaste
Skip_waiting:
MsgBox ("You skipped the second wait")
'Copy&paste script
Copypaste:
Set clip = New DataObject
Set ieTable = ieDoc.all.item
clip.SetText "" & ieTable.outerHTML & ""
clip.PutInClipboard
Sheets("Raw Data").Range("E2").PasteSpecial "Unicode Text"
'Kills all activeX/controls copied from ieDoc.all.item
Sheets("Raw Data").DrawingObjects.Delete
'Kills ALL IE windows
On Error GoTo Ignored:
Call IE_Sledgehammer
Ignored:
End Sub
I do know about the pull data from web option which was my goto on this stuff, but since our office has changed its security settings, its made that option impossible. Other than this, I cannot think of a way to pull data from a click of a button.
Is this option worth it? For anyone with experience with this, Can you tell me if this option is reliable? I cannot for the life of me work out why this is failing.
HTML:
<html><head>
<title>
Open Questions Summary
</title>
<link rel="stylesheet" href="/styles.css" type="text/css">
</head>
<body bgcolor="#FFFFFF">
<table cellspacing="1" cellpadding="2" align="center" border="0" width="400">
<tbody><tr>
<td colspan="2">
Customer Sector:
<form method="get" action="INTERNAL WORK SITE">
<select name="strCustomerType">
<option value="residential" selected="selected">Residential</option>
<option value="business">Business</option>
</select>
<input name="soobmit" value="Submit" type="submit">
</form></table>
From your code and description, it seems that you want to fill value into the textbox and handle the dropdownlist, I suggest you could refer to the following code, they all work well on my machine:
Sub LoginViaBrowser()
Dim IE As Object
Dim Dc_Usuario As String
Dim Dc_Senha As String
Dim Dc_URL As String
Dim txtNam As Object, txtPwd As Object
Dc_Usuario = "user#email.com"
Dc_Senha = "pass"
Set IE = CreateObject("InternetExplorer.Application")
With IE
.Visible = True
.Navigate "https://www.solarmanpv.com/portal/LoginPage.aspx"
While IE.ReadyState <> 4
DoEvents
Wend
IE.Document.getElementById("uNam").Value = Dc_Usuario
IE.Document.getElementById("uPwd").Value = Dc_Senha
IE.Document.getElementById("Loginning").Click
End With
Set IE = Nothing
End Sub
Handle dropdown list:
Public Sub ClickTest()
Dim ie As Object, evtChange As Object
Dim item As Object
Set ie = CreateObject("InternetExplorer.Application")
With ie
.Visible = True
.Navigate2 "<the website url>"
While .Busy Or .readyState <> 4: DoEvents: Wend
Set evtChange = .Document.createEvent("HTMLEvents")
evtChange.initEvent "change", True, False
'get the select element. Please note the index, it is starting from 0.
Set item = ie.Document.getElementsByTagName("select")(0)
expCcy = "EUR"
'Set the Expression Currency
For Each o In item 'Sets Expression Currency
If o.Value = expCcy Then
o.Selected = True
o.dispatchEvent evtChange
Exit For
End If
Next
End With
End Sub
More detail information, please check the following threads: Textbox related thread and DropDownList related thread.

VBA (instagram how to click follow button)?

I am using office 2019. in VBA i am trying to click on follow button. on INSTAGRAM but it did't click on that. simply page open and then nothing will happen.
so, plz help me because it is spine of my project.
Sub one()
Dim IE As Object
Dim doc As HTMLDocument
Dim ele As IHTMLElement
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = 1
IE.navigate "https://www.instagram.com/gal_gadot/"
Do
Loop Until IE.readyState = 4
Set doc = IE.document
'doc.getElementsByTagName("button").innerText
'doc.getElementsByClassName("_5f5mN jIbKX _6VtSN yZn4P ").innerText
For Each ele In doc.getElementsByTagName("span")
' If InStr(ele.innerText, "Follow") > 0 Then ele.Click
On Error Resume Next
If ele.Value = "Follow" Then
ele.Click
End If
Next
For Each ele In doc.getElementsByTagName("button")
' If InStr(ele.innerText, "Follow") > 0 Then ele.Click
On Error Resume Next
If ele.Value = "Follow" Then
ele.Click
End If
Next
End Sub
HERE IS HTML FILE
<span class="BY3EC bqE32">
<span class="vBF20 _1OSdk">
<button class="_5f5mN jIbKX _6VtSN yZn4P ">Follow</button></span>
<span class="mLCHD _1OSdk">
<button class="_5f5mN jIbKX KUBKM yZn4P m4t9r ">
<div class="OfoBO">
<div class="_5fEvj coreSpriteDropdownArrowWhite">
</div>
</div>
</button>
</span>
</span>
The script will help you click on that follow button but you can't follow her until you log in because when you click on that button, it will lead you to the log in page. Btw, you should always define any timed loop so that you can get out of that do loop in case the element is not available. There are several posts in SO which have got it covered.
Sub FollowGalGadot()
Const Url$ = "https://www.instagram.com/gal_gadot/"
Dim IE As New InternetExplorer, post As Object
With IE
.Visible = True
.navigate Url
While .Busy = True Or .readyState < 4: DoEvents: Wend
Do
DoEvents
On Error Resume Next
Set post = .document.querySelectorAll("a[href*='follow'] > button")
On Error GoTo 0
Loop While post.Length = 0
post.item(0).Click
End With
Stop
IE.Quit
End Sub
Thank you, SIM! I’m not a programmer, but I made a little change and it worked great!
Sub FollowGalGadot()
Const Url$ = "https://www.instagram.com/gal_gadot/"
Dim IE As New InternetExplorer, post As Object
With IE
.Visible = True
.navigate Url
While .Busy = True Or .readyState < 4: DoEvents: Wend
While post Is Nothing
On Error Resume Next
Application.Wait Now + TimeValue("00:00:001")
Set post = .document.querySelector("._5f5mN.jIbKX._6VtSN.yZn4P")
If Not post Is Nothing Then
post.Click
Debug.Print "it's done!!!"
Else:
Debug.Print "trying again"
End If
On Error GoTo 0
Wend
End With
Stop
IE.Quit
End Sub

How to get value from webpage?

I want to get/input value to webpage.
All my effort so far works until web loading only. I have no knowledge in web. I can't provide the website link as it's an intranet web.
done lin.e 50 is the place where I want to put my input
then click save button
<td valign="top" class="s bgltgray">
<textarea id="txtResponse1" name="txtResponse1" cols="80" rows="3" class="s">done lin.e 50.</textarea>
<input type="submit" id="cmdRespond1" name="cmdRespond1" value="Save" onclick="cmdRespond_click(1);">
<br> Latest Response By: samyvelu, On: 10/23/2017
</td>
You can try this. Can't really test it since i dont have the url, but this code have worked on another url just without the textarea Tag name
Sub IEtest()
Dim ie As Object
Dim i, x As Integer
Dim objElement As Object
Dim objCollection As Object
Set ie = CreateObject("InternetExplorer.Application")
With ie
.Visible = True
.navigate "" '<--- CHANGE THIS
Do While ie.busy
Application.Wait DateAdd("s", 1, Now)
Loop
Set objCollection = ie.Document.getElementsByTagName("textarea")
i = 0
While i < objCollection.Length
If objCollection(i).Name = "txtResponse1" Then
objCollection(i).Value = "Your input" '<--- CHANGE THIS
End If
i = i + 1
Wend
Set objCollection = ie.Document.getElementsByTagName("input")
i = 0
While i < objCollection.Length
If objCollection(i).Type = "submit" And objCollection(i).Name = "cmdRespond1" Then
Set objElement = objCollection(i)
End If
i = i + 1
Wend
objElement.Click
End With
End Sub
There are ids present. Use those as they are the fastest selector method. Using InternetExplorerMedium object
With ie.document
.getElementById("txtResponse1").value = "yourValue"
.getElementById("cmdRespond1").Click '.Submit
End With

Resources