Automate clicking buttons on one page and then another page using vba - vba

I am trying to work on something that clicks a button\line on a page, then clicks on others when the new page loads. I can get my vba to click the first button/link, but then when trying to click the next I am getting the error
Run-time error 91: Object variable or With block variable not set
Now I have to be honest, the code I do have is from research, and by no means do I understand it fully, I have searched all over trying to rectify the 2nd click, but nothing seems to be working.
the code I have so far is
Public Sub SHAREREPORTING()
Dim IE As SHDocVw.InternetExplorer
Dim Button As Object
Dim Button2 As Object
Set IE = New InternetExplorerMedium
IE.Visible = True
IE.navigate "URL"
Do While IE.ReadyState <> READYSTATE_COMPLETE Or IE.Busy: DoEvents: Loop
Set Button = IE.Document.getElementById("b1_pki")
Button.Click
Application.Wait (Now + TimeValue("0:00:05"))
SendKeys "mypassword" , True
SendKeys "{ENTER}", True
Do While IE.ReadyState <> READYSTATE_COMPLETE Or IE.Busy: DoEvents: Loop
Set Button2 = IE.Document.getElementById("seite-itm-2")
Application.Wait (Now + TimeValue("0:00:05"))
Button2.Click
End Sub
the code for the 2 buttons ( I am calling them buttons/links, because I'm not too sure what they are, I don't understand javascript) I am trying to click at the moment is
Button1/Link1
<A onclick=loginViaPKI(); onkeypress=loginViaPKI(); id=b1_pki title="Log on with PKI - Button - To activate, press spacebar." class=urBtnEmph hideFocus style="WHITE-SPACE: nowrap" href="javascript:void(0);" ct="Button">Log on with PKI</A>
Button2/Link2
<TD onclick="return htmlbSL(this,7,'seite:sel_tab_2','','3','sel_tab_2')" id=seite-itm-2 class=urTbsLabelOff onkeydown="if (sapUrMapi_checkKey(event,'keydown',new Array('32'))){return htmlbSL(this,7,'seite:sel_tab_2','','3','sel_tab_2')};sapUrMapi_TabStrip_keySelect('seite',2,4,event);" noWrap><SPAN id=seite-itm-2-txt title="Bookmarks " class=urTbsTxtOff>Bookmarks </SPAN></TD>

The program requires references to the following:
1 Microsoft Internet Controls
2. Microsoft HTML Object Library
The Internet control is used to browse the webpage and the HTML Objects are used to identify the username and password textboxes and submit the text using the control button.
Dim HTMLDoc As HTMLDocument
Dim oBrowser As InternetExplorer
Sub Login_2_Website()
Dim oHTML_Element As IHTMLElement
Dim sURL As String
On Error GoTo Err_Clear
sURL = "https://www.google.com/accounts/Login"
Set oBrowser = New InternetExplorer
oBrowser.Silent = True
oBrowser.timeout = 60
oBrowser.navigate sURL
oBrowser.Visible = True
Do
' Wait till the Browser is loaded
Loop Until oBrowser.readyState = READYSTATE_COMPLETE
Set HTMLDoc = oBrowser.Document
HTMLDoc.all.Email.Value = "sample#vbadud.com"
HTMLDoc.all.passwd.Value = "*****"
For Each oHTML_Element In HTMLDoc.getElementsByTagName("input")
If oHTML_Element.Type = "submit" Then oHTML_Element.Click: Exit For
Next
' oBrowser.Refresh ' Refresh If Needed
Err_Clear:
If Err <> 0 Then
Debug.Assert Err = 0
Err.Clear
Resume Next
End If
End Sub

Related

Automate editing a field that takes value from a suggester

I tried automating a task on my CRM (using VBA on IE) where there is a field that prompts a suggester as soon as you start typing in it. Even if I enter the exact intended text, the script doesn't save the changes.
Here is the HTML code of the field to be edited:
<input class="itext" size="40" id="txtStrPoblacion" onkeyup="searchPoblacion(this.form, true);" autocomplete="off" value="Sector 14, Gurgaon, Gurgaon" type="text">
And, here is the script that I wrote:
Sub L3()
Dim IE As Object
Dim i As Long
Dim doc As HTMLDocument
Dim oHTML_Element As IHTMLElement
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
For i = 2 To 2
IE.navigate "https://in.nuptic.com/admin/admin-ModificarEmpresa.php?id_empresa=" + Cells(i, 2)
Do While IE.Busy
Application.Wait DateAdd("s", 1, Now)
Loop
Set doc = IE.document
doc.getElementById("txtStrPoblacion").Value = Cells(i, 3)
With IE.document
Set elems = .getElementsByTagName("input")
For Each e In elems
If (e.getAttribute("value") = "Save") Then
e.Click
Exit For
End If
Next e
End With
Next
MsgBox "Done"
End Sub

Issue with clicking on an img button by using alt in IE

I am currently trying to click on a specific img button on a site that does not have an Id so I am trying to click based on the alt. Below is from the DOM Explorer, the alt is in Japanese characters.
<a href="/e-navi/members/statement/index.xhtml?tabNo=0">
<img width="112" height="23" alt="翌月以降" src="https://image.card.jp.rakuten-static.com/r-enavi/WebImages/enavi/common/tab05_after_o.gif">
</a>
The code I am using to try and click the link is:
pUnicodeString = ChrW(32716) & ChrW(26376) & ChrW(20197) & ChrW(38477)
Set tags = ie.document.getElementsByTagName("a")
For Each tagx In tags
If tagx.getAttribute("alt") = pUnicodeString Then
tagx.Click
End If
Next
NOTE: I have also tried it with Set tags = ie.document.getElementsByTagName("img") as well.
When running the code I get the "Permission Denied" error on If tagx.getAttribute("alt") = pUnicodeString Then.
I have been searching on many sites and have tried many peoples past examples but none worked. Below is my full code for reference.
Sub csvfetch()
Dim ie As SHDocVw.InternetExplorer
Dim doc As MSHTML.HTMLDocument
Dim div As HTMLDivElement
Dim url As String
Dim form As Variant
Dim button As Variant
Dim tags As Object
Dim tagx As Object
url = "https://www.rakuten-card.co.jp/e-navi/?l-id=corp_de_enavi_index_001"
Set ie = New SHDocVw.InternetExplorer
With ie
.Visible = True
.navigate url
While .Busy
DoEvents
Wend
End With
While ie.Busy
DoEvents
Wend
Application.Wait (Now + TimeValue("0:00:02"))
'temp user/pass
user = Sheets("Pass").Cells(2, 2)
pass = Sheets("Pass").Cells(2, 3)
ie.document.getElementById("u").Value = user
ie.document.getElementById("p").Value = pass
'login
Set form = ie.document.getElementsByTagName("form")
Set button = form(0).onsubmit
form(0).submit
While ie.Busy
DoEvents
Wend
Set ElementCol = ie.document.getElementsByClassName("rf-button-alt rce-white-button rf-mini")
ElementCol.Item(0).Click
While ie.Busy
DoEvents
Wend
pUnicodeString = ChrW(32716) & ChrW(26376) & ChrW(20197) & ChrW(38477)
Set tags = ie.document.getElementsByTagName("a")
For Each tagx In tags
If tagx.getAttribute("alt") = pUnicodeString Then
tagx.Click
End If
Next
Set ie = Nothing
'Unload UserForm1
End Sub

Using VBA to click a link

I'm trying next to click a link to view information on a page using VBA to then move on to edit that information with VBA, But trying to figure out how to write the code for it as the ID information changes with each search,
Any ideas on this?
I've looked around and can't seem to understand how to get VBA to pick this line up as the (ID=) and it isn't joined to the same ID as I'm searching for.
There is also serval references for
This is the line of code.
View
This is my current code to do the search for it. Without clicking on the view section yet.
Sub Test()
Dim ie As Object
Dim form As Variant
Dim button As Variant
Dim LR As Integer
Dim var As String
LR = Cells(Rows.Count, 1).End(xlUp).Row
For x = 2 To LR
var = Cells(x, 1).Value
Set ie = CreateObject("internetexplorer.application")
ie.Visible = True
With ie
.Visible = True
.navigate "*******"
While Not .readyState = READYSTATE_COMPLETE
Wend
End With
'Wait some to time for loading the page
While ie.Busy
DoEvents
Wend
Application.Wait (Now + TimeValue("0:00:02"))
ie.document.getElementById("quicksearch").Value = var
'code to click the button
Set form = ie.document.getElementsByTagName("form")
Application.Wait (Now + TimeValue("0:00:02"))
Set button = form(0).onsubmit
form(0).submit
'wait for page to load
While ie.Busy
DoEvents
Wend
Next x
End Sub
Edited
I've added in the code I think it should be following that link and a bit of tinkering to get it to not error with compiler errors :D, All seems to work but when it get's to the line to click the link it doesn't fail but doesn't even click it. It will then move on to the next one in the list in the spreed sheet, Which is expected.
Following it through with the debugger that shows nothing erroring or failing which is what I expect it to do if the code was wrong or link,
Any help, please ?
This is the code now
Sub Test1()
Dim ie As Object
Dim form As Variant
Dim button As Variant
Dim LR As Integer
Dim var As String
LR = Cells(Rows.Count, 1).End(xlUp).Row
For x = 2 To LR
var = Cells(x, 1).Value
Set ie = CreateObject("internetexplorer.application")
ie.Visible = True
Dim a
Dim linkhref
linkhref = "/?do_Action=ViewEntity&Entity_ID"
With ie
.Visible = True
.navigate "*******"
While Not .readyState = READYSTATE_COMPLETE
Wend
End With
'Wait some to time for loading the page
While ie.Busy
DoEvents
Wend
Application.Wait (Now + TimeValue("0:00:02"))
ie.document.getElementById("quicksearchbox").Value = var
'code to click the button
Set form = ie.document.getElementsByTagName("form")
Application.Wait (Now + TimeValue("0:00:02"))
Set button = form(0).onsubmit
form(0).submit
'wait for page to load
While ie.Busy
DoEvents
Wend
Application.Wait (Now + TimeValue("0:00:02"))
For Each a In ie.document.getElementsByTagName("a")
If (a.getAttribute("href")) = ("/?do_Action=ViewEntity&Entity_ID=") Then
a.Click
Exit For
Application.Wait (Now + TimeValue("0:00:02"))
While ie.Busy
DoEvents
Wend
End If
Next
Next x
End Sub
This is a copy of the code around the buttons,
This is the code surrounding the buttons,
View
Decom
Log</td>
Thank you.
Use a For to check every <a> tag element and make sure you click the right one. It's true your ID changes, but rest of string is constant, so that's 1 factor. Also, it looks like you always will click where it says View so that's another constant.
With both options, we can develop a simple For..Next that will check every <a> element and will check if those 2 options requirements are fulfilled:
For Each a In ie.document.getElementsByTagName("a")
If Left(a.href, 37) = "/?do_Action=ViewEntity&Entity_ID=" And a.innerText = "View" Then
a.Click
Exit For
Next a
Try it and let's see if this works for you.
If the element href is something like "/?do_Action=ViewEntity&Entity_ID=14287", this if statement is never going to evaluate to True:
(a.getAttribute("href")) = ("/?do_Action=ViewEntity&Entity_ID=")
So the element will never be clicked.
If you know the Entity_ID you want to click you can do:
Dim Entity_ID as Integer
Entity_ID = 14287
If (a.getAttribute("href")) = "/?do_Action=ViewEntity&Entity_ID=" & Cstr(myID) Then a.click
Otherwise just check if the element href contains that url:
If InStr(1, a.getAttribute("href"), linkhref) > 0 Then a.click
EDIT
Ok, using the HTML you posted I am able to access the specified a tag that you requested, by doing this
For Each ele In ie.document.getElementById("searchresults").getElementsByTagName("a")
If InStr(1, ele.href, "do_Action=ViewEntity") > 0 Then
MsgBox "The button is found!"
End If
Next

Log-in to Website

I'm trying to create an Excel macro that will log me into this website. I've written macros to log me into to other websites, but this one is somehow different.
When I use the following code to programmatically insert the username and password and then programmatically click the "log-in" button, the webpage comes back with the message
Error: please provide a username and Error: Please provide a
password
Sub LogIn()
' Open IE and navigate to the log-in page
Set ie = CreateObject("InternetExplorer.Application")
With ie
.Visible = True
.navigate "https://www.prudential.com/login"
' Loop until the page is fully loaded
Do Until Not ie.Busy And ie.ReadyState = 4
DoEvents
Loop
Application.Wait (Now + TimeValue("0:00:10"))
' Enter the necessary information on the Login web page and click the submit button
ie.document.getElementById("username").Value = "abcdef"
ie.document.getElementById("password").Value = "12345678"
ie.document.getElementsByClassName("btn btn-primary btn-login btn-sm-block analytics-login")(0).Click
' Loop until the page is fully loaded
Do Until Not ie.Busy And ie.ReadyState = 4
DoEvents
Loop
End With
' Do stuff
' Quit IE
ie.Quit
End Sub
I can see that my code has inserted the username and password into the webpage boxes, but for some reason after successfully clicking the submit button, the username and password are not being detected.
What code will successfully insert the username and password so that it can be processed by the web page? You'll know that your code works when you get the following error message:
We are unable to verify your username and password. Please try again.
Thanks for your help!
It actually wants you to send a key, so you can bypass this request like this:
ie.document.getElementById("username").Focus
ie.document.getElementById("username").Value = "abcde"
Application.SendKeys "f", True
ie.document.getElementById("password").Focus
ie.document.getElementById("password").Value = "1234567"
Application.SendKeys "8", True
ie.document.getElementsByClassName("btn btn-primary btn-login btn-sm-block analytics-login")(0).Click
Edit:
Sub GetData()
Dim ie As InternetExplorer
Dim desc As IHTMLElement
Set ie = New InternetExplorer
With ie
.navigate "https://www.prudential.com/login"
.Visible = True
End With
Do While (ie.Busy Or ie.ReadyState <> READYSTATE_COMPLETE)
DoEvents
Loop
ie.document.getElementById("username").Focus
Application.SendKeys "abcdef"
Application.Wait (Now + TimeValue("0:00:01"))
ie.document.getElementById("password").Focus
Application.SendKeys "12345678"
Application.Wait (Now + TimeValue("0:00:01"))
ie.document.getElementsByClassName("btn btn-primary btn-login btn-sm-block analytics-login")(0).Click
Set ie = Nothing
End Sub
Try the code below:
Option Explicit
Const READYSTATE_COMPLETE As Long = 4
Const URL_String As String = "https://www.prudential.com/login"
Sub Login()
Dim IE As Object
Dim ObjElement As Object
' using Late Binding
Set IE = CreateObject("InternetExplorer.Application")
With IE
.navigate URL_String
.Visible = True
End With
Do While (IE.Busy Or IE.ReadyState <> READYSTATE_COMPLETE)
DoEvents
Loop
IE.document.getElementByid("username").Value = "abcdef"
IE.document.getElementByid("password").Value = "12345678"
' Optional: I didn't need the wait time
Application.Wait (Now + TimeValue("0:00:01"))
Set ObjElement = IE.document.getElementsByClassName("btn btn-primary btn-login btn-sm-block analytics-login")
ObjElement(0).Click
Set IE = Nothing
End Sub
Another approach might be something like the following.
Sub Get_Logged_In()
Dim IE As New InternetExplorer, HTML As HTMLDocument
Dim post As Object, elem As Object
With IE
.Visible = True
.navigate "https://www.prudential.com/login"
While .Busy = True Or .readyState < 4: DoEvents: Wend
Set HTML = .document
End With
With HTML
Set post = .querySelector("#username")
post.Focus
post.innerText = "abcdef"
Set elem = .querySelector("#password")
elem.Focus
elem.innerText = "12345678"
.querySelector("button[data-qa='Login Button']").Click
End With
IE.Quit
End Sub
Reference to add to the library:
1. Microsoft Internet Controls
2. Microsoft HTML Object Library
In case anyone else has a similar problem I was finally able to get Sendkeys to work. Still, if anyone can come up with a non-Sendkeys solution it would be much preferred.
Two important points in getting Sendkeys to work are 1) use of
Set WSS = CreateObject("WScript.Shell")
and 2) to be sure to run the macro from Excel (e.g. tools-macro-macros) and not from the VB Editor (running from the editor will simply insert the text somewhere within the code and not on the target webpage).
' Open IE and navigate to the log-in page
Application.StatusBar = "Opening IE and logging in to the website"
Set WSS = CreateObject("WScript.Shell")
my_username = "abcdef"
my_pw = "12345678"
Set ie = CreateObject("InternetExplorer.Application")
With ie
.Visible = True
.navigate "https://www.prudential.com/login"
.Top = 0
.Left = 0
.Height = 1025
.Width = 1925
' Loop until the page is fully loaded
Do Until Not ie.Busy And ie.ReadyState = 4
DoEvents
Loop
Application.Wait (Now + TimeValue("0:00:10"))
WSS.SendKeys "{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}"
Application.Wait (Now + TimeValue("0:00:01"))
WSS.SendKeys my_username
Application.Wait (Now + TimeValue("0:00:01"))
WSS.SendKeys "{TAB}"
Application.Wait (Now + TimeValue("0:00:01"))
WSS.SendKeys my_pw
Application.Wait (Now + TimeValue("0:00:01")
ie.document.getElementsByClassName("btn btn-primary btn-login btn-sm-block analytics-login")(0).Click
' Loop until the page is fully loaded
Do Until Not ie.Busy And ie.ReadyState = 4
DoEvents
Loop
End With
' You're now logged in, do your stuff..

Press a link on a webpage using Excel VBA

I have this code where it goes to Minecraft.net and enters the username and password, and then goes to the profile page. I need to change the password on the account, which will be in cell A1 of the worksheet. I can't seem to figure out how to click the change password link. This is my code so far:
Dim IE As Object
Sub submitFeedback3()
Application.ScreenUpdating = False
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
IE.Navigate "https://minecraft.net/login"
Application.StatusBar = "Submitting"
' Wait while IE loading...
While IE.Busy
DoEvents
Wend
' **********************************************************************
IE.Document.getElementById("username").Value = "dddddddd"
IE.Document.getElementById("password").Value = "ddd"
IE.Document.getElementById("signin").Click
'**********************************************************************
Application.StatusBar = "Form Submitted"
Set IE = Nothing
Application.ScreenUpdating = True
End Sub
If the click doesn't work then you could try to submit the html form.
' Add reference to Microsoft Internet Controls
' Add reference to Microsoft HTML Object Library
Set IE = New InternetExplorer
IE.Visible = True
IE.Navigate "https://minecraft.net/login"
While IE.Busy
DoEvents
Wend
IE.Document.getElementById("username").Value = "dddddddd"
IE.Document.getElementById("password").Value = "ddd"
Dim htmlForm As HTMLFormElement
Set htmlForm = IE.Document.getElementById("loginForm")
htmlForm.submit