Select Link on website after login with Excel 2013 VBA - excel

I am trying to open a link on a webpage after logging in with VBA in excel. So far my code successfully opens the website and logs on. However, no examples I've seen in the forums seem to work for actually opening the next link.
HTML Code from the site:
<td class="nrmlFnt nWrap">
<a id="ctl00_wpm_ac_ac_rbk_ctl01_lnkBrokerageAccountName" oncontextmenu="return false;" href="javascript:__doPostBack('ctl00$wpm$ac$ac$rbk$ctl01$lnkBrokerageAccountName','')">Retirement</a>
</td>
While the innertext and ID are unique, I've been unable to select them.
I am new to VBA and may not have been implementing some of the solutions to similar problems quite right. Below is my code:
Dim HTMLdoc As HTMLDocument
Dim MyBrowser As InternetExplorer
Private Sub btnUpdate_click()
'Create Variables for web browsing
Dim MyHTML_Element As IHTMLElement 'Elements to search for: textboxes, buttons etc...
Dim MyURL As String
'Dim IE As InternetExplorerMedium
'Clear errors to prevent from stopping code
On Error GoTo Err_Clear
'Input Desired webpage login URL
MyURL = "https://client.schwab.com/Login/SignOn/CustomerCenterLogin.aspx"
Set MyBrowser = New InternetExplorer 'Creates new browser session
MyBrowser.Silent = True 'Avoids Pop-ups
MyBrowser.navigate MyURL 'Navigates to URL
MyBrowser.Visible = True 'Opens browser window. Change to False to run w/o opening
'Wait for web page to fully load
Do
DoEvents
Loop Until MyBrowser.readyState = READYSTATE_COMPLETE
Set HTMLdoc = MyBrowser.document
'Enter Username:
HTMLdoc.all.ctl00_WebPartManager1_CenterLogin_LoginUserControlId_txtLoginID.Value = "username"
'Enter Password:
HTMLdoc.all.txtpassword.Value = "password"
'Click Login button on webpage:
For Each MyHTML_Element In HTMLdoc.getElementsByTagName("a")
If MyHTML_Element.ID = "ctl00_WebPartManager1_CenterLogin_LoginUserControlId_btnLogin" Then MyHTML_Element.Click: Exit For
Next
'Wait for web page to fully load
Do
DoEvents
Loop Until MyBrowser.readyState = READYSTATE_COMPLETE
'Select Account to be displayed:
Set HTMLdoc = MyBrowser.document
Set e = HTMLdoc.getElementById("ctl00_wpm_ac_ac_rbk_ctl01_lnkBrokerageAccountName")
e.Click
'Wait for web page to fully load
Do
DoEvents
Loop Until MyBrowser.readyState = READYSTATE_COMPLETE
'Define Err_Clear Function:
Err_Clear:
If Err <> 0 Then
Err.Clear
Resume Next
End If
End Sub
I feel this should be something pretty simple like the following, but it hasn't worked:
Set MyHTML_Element= MyBrowser.Document.getElementByID("ctl00_wpm_ac_ac_rbk_ctl01_lnkBrokerageAccountName").getElementsByTagName("a")(0)
MyHTML_Element.Click
I have also tried the following with no success:
For Each MyHTML_Element In HTMLdoc.getElementsByTagName("a")
If MyHTML_Element.ID = "ctl00_wpm_ac_ac_rbk_ctl01_lnkBrokerageAccountName" Then MyHTML_Element.Click: Exit For
Next
The webpage loads, logs in and then... nothing happens.

So I got it to work finally. I apparently needed the webpage to finish loading and the simple "READYSTATE_COMPLETE" didn't cut it. So I ended up with this to make sure the page fully loaded:
With MyBrowser
Do While .Busy Or .readyState <> 4
DoEvents
Loop
End With
And then I used the following code to select the link:
Set HTMLdoc = MyBrowser.document
Set e = HTMLdoc.getElementById("ctl00_wpm_ac_ac_rbk_ctl01_lnkBrokerageAccountName")
e.Click
It finally goes to the correct page! Now I just need to pull the correct data... easy right?

Related

Click on Class names in VBA - No Selenium

I am into Project Management with no knowledge of IT / Coding.
I am trying to do web automation.
It will have to click on certain links, submit a form and then hit save.
However I am not able to click on the first link as well.
this is my code as of now.
Sub CommandButton1_Click()
Dim ie As Object
Dim html As HTMLDocument
Dim form As Variant, button As Variant
Sheet1.Range("B6").Value = Application.UserName
'Open Internet Explorer
Set ie = CreateObject("InternetExplorer.Application")
ie.navigate "https://www.link.com/"
ie.Visible = True
While ie.Busy
DoEvents
Wend
Set html = ie.document
html.getElementsByClassID("p2205").Click
End Sub
Below is the code.
I want to click on Company Name.
Website Code
I have tried the web and YouTube videos as well but I guess I don't know the language or the logic behind coding. Hence I am not able to get through.
Add reference to Microsoft Internet Controls then try
Option Explicit
Sub CommandButton1_Click()
Dim ie As Object, html As HTMLDocument, e As HTMLHtmlElement
Dim URL As String
URL = "https://www.link.com/"
Set ie = New InternetExplorerMedium
ie.navigate URL
ie.Visible = True
While ie.Busy
DoEvents
Wend
Set html = ie.document
For Each e In html.getElementsByClassName("dsh_sta_301")
If InStr(e.onclick, "projectSelection") > 0 Then
e.Click
End If
Next
End Sub

Filling web form fields but web page unable to detect text

I'm filling a web form using VBA, and I am able to fill text in the inputbox, but the webpage still is unable to detect the text and shows an error:
"Error: Required Field - Please provide an answer"
Set objIE = CreateObject("InternetExplorer.Application")
objIE.Visible = True
URL = "https://npc.collegeboard.org/app/dartmouth/start"
objIE.Navigate URL
objIE.Document.getElementById("student.firstName").Focus
objIE.Document.getElementById("student.firstName").Value = "Tom"
Looks like theres some AngularJS running in the background, and it can't detect text fed in my VBA. Any help would be highly appreciated.
First of all after objIE.Navigate URL you should wait until the website is fully loaded and the IE is ready. This is done with the following:
objIE.Navigate URL 'this needs some time but VBA will continue excecuting the next statement qickly
Const READYSTATE_COMPLETE As Integer = 4
Do While objIE.Busy Or objIE.ReadyState <> READYSTATE_COMPLETE
DoEvents
Loop
'now IE is ready and the page is loaded.
But it might be that some JavaScript is not ready yet and this is not recognized by objIE.Busy Or objIE.ReadyState. So you can do a workaround:
Dim Obj As Object
Do While Obj Is Nothing
On Error Resume Next
Set Obj = objIE.Document.getElementById("student.firstName")
On Error GoTo 0
Loop
'now `student.firstName` is accessible, and probably all the other fields are too.
This will try to access the field student.firstName if it is not there it will error. We suppress the error message using On Error Resume Next and jump back to TryAgain until it was found.
Note that this has one disadvantage: If there is a problem loading this site it will get stuck in this loop. So I recommend to get a timed cancel criterium like if this takes more than a minute cancel it and throw a error message.
Something like the following should work:
Option Explicit
Sub test()
Dim objIE As Object
Set objIE = CreateObject("InternetExplorer.Application")
objIE.Visible = True
Dim URL As String
URL = "https://npc.collegeboard.org/app/dartmouth/start"
objIE.Navigate URL
Const READYSTATE_COMPLETE As Integer = 4
Do While objIE.Busy Or objIE.ReadyState <> READYSTATE_COMPLETE
DoEvents
Loop
Dim Obj As Object
Do While Obj Is Nothing
On Error Resume Next
Set Obj = objIE.Document.getElementById("student.firstName")
On Error GoTo 0
Loop
objIE.Document.getElementById("student.firstName").Focus
objIE.Document.getElementById("student.firstName").Value = "Tom"
End Sub

How to enter data into an Internet Explorer website?

I am trying to enter info into an Internet Explorer 11 website form. The website/form was designed a long time ago (around 15-20 years). The website can only be accessed through Internet Explorer.
I cannot share the website/source code as it is internal to my company.
I have browsed online for a solution, but none worked (I tried many different versions).
I am looking to login, then go through a few pages of entering information, while clicking next/submit at each stage. I am failing after I login.
I have the following references on Excel:
Microsoft Internet Controls, Microsoft HTML Object Library, Microsoft XML, v6.0
I am following the wise owl tutorial https://www.youtube.com/watch?v=dShR33CdlY8. Skip to about 17 mins in to see where I got the code.
I got an error message at the line htmlinput.Value = "excel".
The error message was
object variable or with block variable not set - Run Time error '91'
Sub navigate_website()
Dim ie As New SHDocVw.InternetExplorer
Dim htmldoc As MSHTML.HTMLDocument
Dim htmlinput As MSHTML.IHTMLElement
ie.Visible = True
ie.navigate Sheet1.Range("C2").Text
Do While ie.Busy Or ie.readyState <> READYSTATE_COMPLETE
DoEvents
Loop
'enter in userid
ie.document.forms("formsamplename").elements("usedid").Value = ThisWorkbook.Sheets("sheet1").Range("B6")
'enter in password
ie.document.forms("formsamplename").elements("userpassword").Value = ThisWorkbook.Sheets("sheet1").Range("B7")
'click the login button
ie.document.forms("formsamplename").elements("cmdSubmit").Click
Do While ie.Busy Or ie.readyState <> READYSTATE_COMPLETE
DoEvents
Loop
' ----- I tried the below code as an alternative but it didn't work -----
'ie.document.forms("formsamplename").elements("usernumber").Value = ThisWorkbook.Sheets("sheet1").Range("B6")
Set htmldoc = ie.document
Set htmlinput = htmldoc.getElementById("usernumber")
htmlinput.Value = "excel" **'error occurs here**
' ----- I also tried the below code, but it didn't work -----
'htmldoc.forms("formsamplename").elements("usernumber").Value = "test"
Set ie = Nothing
Set htmldoc = Nothing
Set htmlinput = Nothing
End Sub

How to submit login credentials?

This is relating to the submit button of the login screen
HTML:
<TD background=/frontend/images/greenback.gif width=302><INPUT type=submit value="Login now" name=submit> </TD>
I enter the username and password into the box but the script stops at .Submit
Sub GetTable()
'Kills any open 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
'Create anew instance of ie
Set ieApp = New InternetExplorer
'Debugging
ieApp.Visible = True
'Opening this page prompts login screen
ieApp.Navigate "CANNOT SHARE, INTERNAL WORK SITE"
'When busy - wait
Do While ieApp.Busy: DoEvents: Loop
Do Until ieApp.ReadyState = READYSTATE_COMPLETE: DoEvents: Loop
'Pop up window
On Error GoTo skip_Popup
ieApp.Document.all.item("submitBn").Focus
SendKeys "~"
skip_Popup:
'Login script
On Error GoTo Skip_Login
Set ieDoc = ieApp.Document
'fill in the login form – View Source from your browser to get the control names
With ieDoc.forms(0)
.UserName.Value = "test1"
.Password.Value = "test2"
.Submit
End With
Do While ieApp.Busy: DoEvents: Loop
Do Until ieApp.ReadyState = READYSTATE_COMPLETE: DoEvents: Loop
Skip_Login:
'Copy page Info
Set ieDoc = ieApp.Document
Set ieTable = ieDoc.all.item
'Copy Paste the page
If Not ieTable Is Nothing Then
Set clip = New DataObject
clip.SetText "" & ieTable.outerHTML & ""
clip.PutInClipboard
'Location of data
Sheets("Raw Data").Range("E2").PasteSpecial "text"
End If
'Delete any form controls that make it into the sheet
Sheets("Raw Data").DrawingObjects.Delete
'Kills ALL IE windows
Call IE_Sledgehammer
Set ieApp = Nothing
End Sub
Also this is not critical, how do I just select the table on the page and not everything else? It doesn't have a name so I am stuck with this one also.
HTML:
<table cellspacing="1" cellpadding="2" align="center" border="0" width="400">
Try using attribute = value css selector
ie.document.querySelector("[name=submit]").click
For your table your best bet is to locate it by it's relationship to other elements/attributes. Impossible to advise further without seeing more html. Failing that if there is a unique attribute or attribute=value in that table (not present in other tables) then combine that to id the table
e.g.
ie.document.querySelector("table[width='400']")
This is a less robust method.
I tested your code and I am able to produce the issue.
As an alternative, you can try to loop through input elements and try to find the submit and click it.
Set objCollection = ieApp.document.getElementsByTagName("input")
i = 0
While i < objCollection.Length
If objCollection(i).Type = "submit" And _
objCollection(i).Name = "submit" Then
objCollection(i).Click
End If
i = i + 1
Wend

How is it possible to click on a button present in a newly opened tab in internet explorer using VBA?

Here is the code I wrote.
Option Explicit
Public Sub Press_Button()
Dim objIE As SHDocVw.InternetExplorer 'microsoft internet controls (shdocvw.dll)
Dim htmlDoc As MSHTML.HTMLDocument 'Microsoft HTML Object Library
Dim htmlInput As MSHTML.HTMLInputElement
Dim htmlColl As MSHTML.IHTMLElementCollection
Dim the_input_elements As MSHTML.IHTMLElementCollection
Dim input_element As MSHTML.HTMLInputElement
Dim IeDoc As MSHTML.HTMLDocument
Dim IeDoc2 As MSHTML.HTMLDocument
Dim input_element2 As MSHTML.HTMLInputElement
Dim the_input_elements2 As MSHTML.IHTMLElementCollection
Set objIE = New SHDocVw.InternetExplorer
With objIE
.Navigate "https://www.ndexsystems.com/fengine/fullservice/en/kerrfinancialsalogin.go?fromLogoff=true" ' Main page
.Visible = 1
Do While .readyState <> 4: DoEvents: Loop
Application.Wait (Now + TimeValue("0:00:02"))
'PART 1: set user name and password
Set htmlDoc = .document
Set htmlColl = htmlDoc.getElementsByTagName("INPUT")
Do While htmlDoc.readyState <> "complete": DoEvents: Loop
For Each htmlInput In htmlColl
If htmlInput.Name = "textbox_password" Then
htmlInput.Value = "***"
Else
If htmlInput.Name = "textbox_id" Then
htmlInput.Value = "***"
End If
End If
Next htmlInput
'PART 2: click login
Set htmlDoc = .document
Set htmlColl = htmlDoc.getElementsByTagName("input")
Do While htmlDoc.readyState <> "complete": DoEvents: Loop
For Each htmlInput In htmlColl
If Trim(htmlInput.Type) = "submit" Then
htmlInput.Click
Exit For
End If
Next htmlInput
'PART 3: Clicks on portfolio management button
Do While .Busy: DoEvents: Loop
Do Until .readyState = READYSTATE_COMPLETE: DoEvents: Loop
Set IeDoc = .document
Set the_input_elements = IeDoc.getElementsByClassName("big_button")
For Each input_element In the_input_elements
If input_element.href = "javascript:changePageToFrontdoor(false);" Then
input_element.Click
Exit For
End If
Next input_element
'PART 4: Clicks on the 'Advanced search' button
Do While .Busy: DoEvents: Loop
Do Until .readyState = READYSTATE_COMPLETE: DoEvents: Loop
Set IeDoc2 = .document
Set the_input_elements2 = IeDoc2.getElementsByClassName("parent-item")
For Each input_element2 In the_input_elements2
If input_element2.href = "javascript:directToSearch()" Then
input_element2.Click
Exit For
End If
Next input_element2
End With
End Sub
Parts 1, 2 and 3 work perfectly. When I run this macro, it is actually logging in the website with my credentials. In part 3, it is also clicking on the button called "Porfolio management".
However, by clicking on the "portfolio management" button, a new tab is opened with another page of the same website.
On this newly opened page, there is a button called "Advanced search" that I want to click. Here is the HTML code of the button.
Part 4 is not working with this code. It is not giving me any error, it is just not doing anything. I don't know where my error is because I wrote part 4 with the exact same syntax as part 3 and it is only part 3 that is actually running and giving the correct result (clicking on the button).
Maybe the fact that part 3 opens a new tab of this website should imply an additional step that I didn't do in step 4? Since I am not working with the same tab anymore...
Can anyone help me with finding the error?
Thank you :)
If the URL is different every time and you are not available with that URL than you can try to refer steps below.
(1) create object of Shell application.
(2) Than try to count IE windows and loop through it.
(3) After that match the page title with all the tabs and find the desired tab and assigned it to IE object and than you can try to interact with that page.
Example:
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
'find the desired page
If my_title Like "Put something from your IE page title here" & "*" Then
Set ie = objShell.Windows(x)
Exit For
Else
End If
Next
You can modify the above code based on your requirement.
For more information, you can refer link below.
VBA-Excel: Get ALL The Opened Internet Explorer (IE) using Microsoft Excel

Resources