using VBA to interact with webpages - vba

I've found some code online to use VBA to interact with Webpages and have since tweaked it. I'm trying to auto login to a website, then pull some reports...
Here's the code I have so far..
Private Sub IE_Automation()
Dim i As Long
Dim IE As Object
Dim objElement As Object
Dim objCollection As Object
' Create InternetExplorer Object
Set IE = CreateObject("InternetExplorer.Application")
' You can uncomment Next line To see form results
IE.Visible = True
' Send the form data To URL As POST binary request
IE.Navigate "https://e-oscar-web.net/EntryController?trigger=Login"
' Statusbar
'Application.StatusBar = "www.e-Oscar.com is loading. Please wait..."
' Wait while IE loading...
Do While IE.Busy
Application.Wait DateAdd("s", 1, Now())
Loop
Set objCollection = IE.document.getElementsByTagName("input")
i = 0
While i < objCollection.Length
If objCollection(i).ID = "companyId" Then
' Set text for search
objCollection(i).Value = "compId"
Else
If objCollection(i).ID = "userId" Then
objCollection(i).Value = "uId"
Else
If objCollection(i).ID = "password" Then
objCollection(i).Value = "pwd"
Else
If objCollection(i).ID = "securityMsgAck1" Then
objCollection(i).Value = True
'Else
'If objCollection(i).Type = "button" Then
'objCollection(i).Value = True
' "Search" button is found
Set objElement = objCollection(i)
End If
End If
End If
End If
'End If
i = i + 1
Wend
objElement.Click ' click button to search
' Wait while IE re-loading...
Do While IE.Busy
Application.Wait DateAdd("s", 1, Now)
Loop
' Show IE
IE.Visible = True
' Clean up
Set IE = Nothing
Set objElement = Nothing
Set objCollection = Nothing
Application.StatusBar = ""
End Sub
This seems to be working fine. It pulls the webpage up, fills out the three input boxes, then appears to "check" the radio button that I've acknowledged the terms and agreements, but when I uncomment out
'Else
'If objCollection(i).Type = "button" Then
'objCollection(i).Value = True
The webpage gives me an error:
◾LOGIN ERROR: Security messages must be acknowledged by authorized
users to access e-OSCAR. Please try again.
like the radio button wasn't click, however, I can clearly see it's clicked. I commented that piece out, then ran it, the webpage pulls up with all 3 input boxes filled out, and the radio button checked. When I click "Login" it throws the same error. So it must be with the radio button itself or the way I'm trying to "click" it, not the code that's actually clicking the button "Login"
Does anyone have any thoughts (or recommendations that may resolve this) on why this might be happening?
- IE 11
- Excel 2013

Related

How to click button when navigating website?

I'm trying to open a website, login, select report, and save in Excel format.
I managed to open IE, navigate to the site, enter Username/Password and login.
How do I select the webpage button to open the report page?
Below is the portion of the button on the website I'm attempting to click and code I've tried, both do not give any error message they simply don't do anything.
Website HTML
Sub vbamacro()
Dim IE As Object
Dim IEPage As Object
Dim IEPageElement As Object
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
'Enter website name below
IE.Navigate "websitename"
'Ready state means wait until the website has loaded
Do Until IE.ReadyState = 4
DoEvents
Loop
Set IEPage = IE.Document
Set IEPageElement = IEPage.getElementById("ctl00__contentPlaceHolder__txtUserID")
IEPageElement.Value = "username"
Set IEPageElement = IEPage.getElementById("ctl00__contentPlaceHolder__txtPassword")
IEPageElement.Value = "password"
Set IEPageElement = IEPage.getElementById("ctl00__contentPlaceHolder__btnLogin")
IEPageElement.Click
Do Until IE.ReadyState = 4
DoEvents
Loop
With IE.Document
Set elems = .getElementsByTagName("Li")
For Each e In elems
If (e.getAttribute("ID") = "Reports3") Then
e.Click
Exit For
End If
Next e
End With
End Sub
Also tried;
For each e in ie.document.getElementsByTagName("Li")
If e.ID = "Reports3" Then
e.Click
Exit For
End If
Next
Try navigating directly to the href of the desired element
IE.navigate(e.href)
Also you are clicking “Li” tag element, you have to get the Li children’s tag witch is “a” (the one that has the href property)

.Click action not doing anything - IE Simulation

I'm trying to simulate the interaction with Google through the IE app and going through the DOM to get the classes I need and all is fine, stepping though the code, except the .Click action which doesn't cause a crash but it doesn't do anything (page doesn't navigate) - Code and screenshot of HTML below:
Option Explicit
Private Sub Test_Automation()
Dim ie, doc, eInput, eButton, eButtons As Object
Dim sURL, sTest As String
Set ie = CreateObject("internetexplorer.application")
sURL = "https://www.google.co.uk/?gfe_rd=cr&ei=IpDvWK72LsjCaJCbjKAL&gws_rd=ssl"
sTest = "Test"
With ie
.Visible = True
.Navigate sURL
End With
Do While ie.Busy Or ie.readyState <> 4
DoEvents
Loop
Set doc = ie.document
Set eInput = doc.getElementByid("lst-ib")
Set eButtons = doc.getElementsByTagName("input")
eInput.Value = sTest
For Each eButton In eButtons
If (eButton.getattribute("name") = "btnK") Then
eButton.Click
Exit For
End If
Next
End Sub
Any advise on what I'm doing wrong would be great!
You can get rid of your For...Next loop at the bottom and replace it with this to click the button:
doc.forms(0).submit
The 0 can be changed to another number (such as 1 or 2) to click on a different button. If there are multiple buttons on a page that can be clicked on it will just take some trial and error to find out which number matches the button you want to click.

How to pause Excel VBA and wait for user interaction before loop

I have a VERY basic script I am using with an excel spreadsheet to populate a form. It inserts data into the fields then waits for me to click the submit button on each page. Then it waits for the page to load and fills in the next set of fields. I click submit, next page loads, etc. Finally, on the last two pages I have to do some manual input that I can't do with the spreadsheet. Code thus far is shown below.
My question is, at the end of what I have there now, how can I make the system wait for me to fill out that last page, then once I submit it realize that it has been submitted and loop back to the beginning, incrementing the row on the spreadsheet so that we can start over and do the whole thing again for the next student?
As you will probably be able to tell I am not a programmer, just a music teacher who does not savor the idea of filling out these forms manually for all 200 of my students and got the majority of the code you see from a tutorial.
Function FillInternetForm()
Dim IE As Object
Set IE = CreateObject("InternetExplorer.Application")
'create new instance of IE. use reference to return current open IE if
'you want to use open IE window. Easiest way I know of is via title bar.
IE.Navigate "https://account.makemusic.com/Account/Create/?ReturnUrl=/OpenId/VerifyGradebookRequest"
'go to web page listed inside quotes
IE.Visible = True
While IE.busy
DoEvents 'wait until IE is done loading page.
Wend
IE.Document.All("BirthMonth").Value = "1"
IE.Document.All("BirthYear").Value = "2000"
IE.Document.All("Email").Value = ThisWorkbook.Sheets("queryRNstudents").Range("f2")
IE.Document.All("Password").Value = ThisWorkbook.Sheets("queryRNstudents").Range("e2")
IE.Document.All("PasswordConfirm").Value = ThisWorkbook.Sheets("queryRNstudents").Range("e2")
IE.Document.All("Country").Value = "USA"
IE.Document.All("responseButtonsDiv").Click
newHour = Hour(Now())
newMinute = Minute(Now())
newSecond = Second(Now()) + 3
waitTime = TimeSerial(newHour, newMinute, newSecond)
Application.Wait waitTime
IE.Document.All("FirstName").Value = ThisWorkbook.Sheets("queryRNstudents").Range("a2")
IE.Document.All("LastName").Value = ThisWorkbook.Sheets("queryRNstudents").Range("b2")
IE.Document.All("Address1").Value = "123 Nowhere St"
IE.Document.All("City").Value = "Des Moines"
IE.Document.All("StateProvince").Value = "IA"
IE.Document.All("ZipPostalCode").Value = "50318"
End Function
I would use the events of the IE, more specifically the form, something like this, using MSHTML Controls library.
Private WithEvents IEForm As MSHTML.HTMLFormElement
Public Sub InternetExplorerTest()
Dim ie As SHDocVw.InternetExplorer
Dim doc As MSHTML.HTMLDocument
Set ie = New SHDocVw.InternetExplorer
ie.Visible = 1
ie.navigate "http://stackoverflow.com/questions/tagged/vba"
While ie.readyState <> READYSTATE_COMPLETE Or ie.Busy
DoEvents
Wend
Set doc = ie.document
Set IEForm = doc.forms(0)
End Sub
Private Function IEForm_onsubmit() As Boolean
MsgBox "Form Submitted"
End Function

Need to use VBA to select an option from a drop down list in Internet Explorer

I have successfully got my code to open IE, navigate to the webpage I need, and login. I now need to select an option from a drop down list - please see the following html code:
html code for the list
How do I select the "TPS Managed Conservative - Dec 11" option from the dropdown.
My code so far:
Sub Strategic_Alpha_Monthly_Pivots_1_MASTER()
' open IE, navigate to the desired page and loop until fully loaded
Dim ie As Object
Set ie = CreateObject("InternetExplorer.Application")
my_url = "http://analytics.financialexpress.net/login.aspx"
With ie
.Visible = True
.navigate my_url
Do Until Not ie.Busy And ie.readyState = 4
DoEvents
Loop
End With
' Input the userid and password
ie.document.getElementById("txtPassword").Value = "xxxxx"
' Click the "Search" button
ie.document.getElementById("btnAction").Click
Do Until Not ie.Busy And ie.readyState = 4
DoEvents
Loop
ie.document.getElementById("ListPortfolio").Select
End Sub
selectedIndex or Value could be used. According to the screenshot the value 983678630 can be used. HTH
If Not VBA.IsNull(ie.document.getElementById("ListPortfolio")) Then
Dim htmlSelect
Set htmlSelect = ie.document.getElementById("ListPortfolio")
' htmlSelect.selectedIndex = 6
htmlSelect.Value = 983678630
Else
MsgBox "Element 'ListPortfolio' was not found", vbExclamation
End If

VBA click a specific button

I'm trying to get a program to access a website, type in a zip code, add the zip code then press a button to get to the next page. My code is below.
Now I'm stuck on this page and can't get the program to click on the "Property" tab and go to the next page I want to see. Can I get any help on clicking on this button?
I've tried .GetElementsbyID("").click but that doesn't seem to work...
Web page code around the button I want to press:
<span class="geographymap-span-tab" id="tab_PROPERTY_PAGE" onclick="showSearchTypeSection('PROPERTY_PAGE','PROPERTY')"><img id="PROPERTY_PAGE_IMG" src="/list/images/PROPERTY_PAGE_2.gif" alt="property" width="80" height="29" border="0" onmouseover="MM_swapImage('PROPERTY_PAGE')" onmouseout="MM_swapImgRestore('PROPERTY_PAGE')"></span>
My code thus far is below:
Sub TestProgram()
Dim i As Long
Dim IE As Object
Dim objElement As Object
Dim objCollection As Object
' Create InternetExplorer Object
Set IE = CreateObject("InternetExplorer.Application")
' You can uncoment Next line To see form results
IE.Visible = True
' Send the form data To URL As POST binary request
IE.Navigate "http://www.listsource.com/build.marketing.list"
' Statusbar
Application.StatusBar = "www.listsource.com is loading. Thanks and Gig 'em..."
' Application.StatusBar = False
' Wait while IE loading...
Do While IE.Busy
Application.Wait DateAdd("s", 1, Now)
Loop
'Focus on the drop down menu
IE.document.getElementByID("locator").Focus
'Select zip code which happens to be the 19th item
IE.document.getElementByID("locator").selectedIndex = 19
'Get to the right page based on that selection
IE.document.getElementByID("locator").FireEvent ("onchange")
'input zipcode
Do While IE.Busy
Application.Wait DateAdd("s", 1, Now)
Loop
Application.StatusBar = "Search form submission. Please wait..."
Set objCollection = IE.document.getElementsByTagName("textarea")
i = 0
While i < objCollection.Length
If objCollection(i).Name = "zipTextArea" Then
' Set text for search
objCollection(i).Value = "75225"
Else
If objCollection(i).Type = "button" And _
objCollection(i).Name = "addZip" Then
' "Search" button is found
Set objElement = objCollection(i)
End If
End If
i = i + 1
Wend
' pull all elements that are buttons
Set objInputs = IE.document.getElementsByTagName("button")
'click button
For Each ele In objInputs
If ele.Name Like "addZip" Then
ele.Click
End If
Next
' Wait while IE re-loading...
Do While IE.Busy
Application.Wait DateAdd("s", 1, Now)
Loop
' FIND OUT total # of SFR in each given zip code
' Click on "Property" button
End Sub
What can I add to click on the Property Tab?
Or you could check the form (searchform) for all elements named "addzip" and click on the first it encounters.
'(Dim frm as object)
'(Dim btnAdd as object)
Set frm = IE.document.forms("searchform")
Set btnAdd = frm.all("addzip")(0)
btnAdd.click