VBA Automate IE: element.click and element.FireEvent (OnClick) Not working - vba

I am trying to parse a web based pivot table.
Unfortunately, I need to expand additional lines in the web based pivot table in order to access all the data I need. I think that when I click on the + sign to expand additional lines, a script downloads the additional data from the database.
Anyway, here is the html code of the + sign:
<DIV class="clip9x9 di-img" onclick=_Ewa.Gim.tpdfce(event);>
<INPUT title=Expand class=ewaboot_expand type=image alt=Expand src="http://...">
</DIV>
I manage to get the correct element into an variable using IE.document.getElementsByTagName("Div") and a If Loop (for some reason the GetElementByClassName would crash my IE), but none of the .Click or .FireEvent (OnClick) methods works. I also tried both methods on the Input element below the DIV, and these are not working either.
Here is the code
Sub Test()
Dim IE As InternetExplorer
Dim div As Variant
Dim Obj As Variant
Dim WebUrl As String
WebUrl = "http://..../filename.aspx"
Set IE = New InternetExplorerMedium
Sleep 1000
IE.Visible = True
IE.navigate WebUrl
Do While IE.Busy Or IE.readyState <> READYSTATE_COMPLETE
Sleep 1000
Loop
Set div = IE.document.getElementsByTagName("Div")
For Each Obj In div
If Obj.className = "clip9x9 di-img" Then
Obj.Click
Obj.FireEvent ("OnClick")
End If
Next i
End Sub
When I look at the onclick attribute of my Obj element in th Spy Window (VBA editor), the onclick property has a + sign aside, and when inspecting inside it, no variable is attributed to it. I find it weird since the HTML code indicates a value =”_Ewa.Gim.tpdfce(event);” which I believe refers to the script that expands the pivot table line.
Any help would be much appreciated

Related

Checking if HTML elements exists after a input with VBA does not work correctly using html.getElementById()

I am pretty new to VBA and don't have much experience with it.
I have a excel sheet with more then 500 commands for which I want to test if the syntax of the command is correct. To do so I thought about using VBA to automate this process.
For the start I went with just one command to see if it could work, but it does not. My code:
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
URL = "https://www.freeformatter.com/java-regex-tester.html"
IE.Navigate URL
While IE.ReadyState <> 4
DoEvents
Wend
IE.Document.getElementById("regex").Value = "\b(Yes"
IE.Document.getElementById("input").Value = "Yaes"
IE.Document.getElementById("matchesButton").Click
While IE.ReadyState <> 4
DoEvents
Wend
Set html = IE.Document
If IsNull(html.getElementById("output")) Then
Worksheets(12).Range("A2").Interior.ColorIndex = 3
End If
Set IE = Nothing
The input "\b(Yes" should be with syntax errors, so there should be this HTML code:
<div id="output" class="form-wrapper" style="margin-top:20px;padding-left:20px;">
But checking this id="ouptut" does not work, with this error there should no <div id="output" be and therefore IsNull(html.getElementById("output")) should return a Null/True and the excel cell should be marked red.
Can anyone please help me out with my logic error in the code? I tried already hours and should be simple, but I was not able to find a solution via google.
From this post here, you need to check if the object exists rather than if the element is null.
Create the object first
set Element = html.getElementByID("output")
Then run your check to see if the object exists
if isObject(Element) then
Try that.

Starting JavaScript query in IE from VBA

I am trying to develop a macro that will be able to automatically check the format of tracking number in a sheet, decide which courier site to use, and then get the status of shipment. Until now it's going pretty well, since both tnt and dhl's results have tracking no in it's address, but I got kinda stuck with ups, where the submission of form seems to be done via javascript.
I managed to trick it by focusing on input box and making my macro send keys tab, tab and enter after inputting no, but it's not so elegant and the success rate seems to be about 70% from my testing.
I tried all different variations of getelementsby..., but nothing really seemed to submit the form successfully.
Is there a way to call the JavaScript to start query, or maybe another way of submitting the form itself?
Added an edited chunk of code for testing as well as html for both what seems to be code for the button and for the JavaScript :
sub ups()
Dim objIE
Dim Website
Dim Element
Dim cRng As Range
Set cRng = "1Z30RY119130505965"
Set objIE = "https://www.ups.com/tracking/tracking.html"
With objIE
.visible = True
.navigate Website
Do While objIE.Busy Or objIE.ReadyState <> 4
DoEvents
Loop
Set Element = .Document.GetElementsByName("trackNums")
'a part of code I found useful for when previous Do
'While fails and events start executing too early
Dim btimer As Integer
btimer = 0
Do While Element.Item(3).Value = 0
Application.Wait (Now + TimeValue("0:00:01"))
btimer = 4 Then
Exit Do
End If
Loop
Element.Item(3).Focus
Element.Item(3).Value = cRng.Value
SendKeys "{TAB}"
SendKeys "{TAB}"
SendKeys "{~}"
<div class="btnBar">
<input name="track.x" class="ups-cta ups-cta_primary" type="submit" value="Track"></input>
</div>
<script language="JavaScript1.2" type="text/javascript">
$(function)
{
Tracking.setLocaleString('en_KR');
Tracking.setLoadingText('Loading. Please wait a moment.');
Tracking.setErrorMessage3('The systen is unable to process your request at this time. Please try again later.');
Tracking.addInatructionTextForyinputPage("Enter up to 25 tracking or InfoNotice numbers, one per line.", 'y');
Thanks for any ideas in advance.

Click on picture or link behind it

Hi I have macro which supposed to click on button on web page..problem is there is no ID behind just this code. Its intranet web page.
Begining of my code
Set IE = New InternetExplorerMedium
IE.Navigate = "some website"
While IE.ReadyState <> READYSTATE_COMPLETE
DoEvents
Wend
IE.Visible = True
IE.document.getElementById("CategoryCombo").Value = "78"
IE.document.getElementById("CategoryCombo").FireEvent ("onchange")
'~~> wait until element is present on web page
Do
Set ieobj = Nothing
On Error Resume Next
Set ieobj = IE.document.getElementById("text1265")
DoEvents
Loop Until Not ieobj Is Nothing
'~~> search box
IE.document.getElementById("text1265").Value = "some value"
'~~> button click example
IE.document.getElementById("subBtn").Click
Part of website code
<a title="View document" href="javascript:FSResults_fsopenWindow('index.fsp?pn=DOLViewDocument&d=78&q=78-17158635-1&o=78-17158635-1&p=DOCUMENT_NAME#ensureVisible')" onclick="fsCancelEvent(event)"><img border="0" alt="View document" align="absmiddle" src="Images/DocTypes/PDF.gif"></a>
I tried
IE.document.getElementByTitle("View document").FireEvent ("onclick")
I also tried
IE.document.getElementByTagName("a").FireEvent ("onclick")
Thank you
I also tried
IE.document.getElementByTagName("a").FireEvent ("onclick")
This should work for you, but you are missing something. You need to specify which <a> tag you are looking for, so .getElementsByTagName("a") turns into .getElementsByTagName("a")(i), where i is the index of the tag you are looking for (you get the index by counting in order every <a> tag in the HTML, starting from 0).
The index is needed because .getElementsByTagName("tagName") returns an array, not a single value.
You could have used CSS selectors.
For example, an attribute selector
ie.document.querySelector("[title='View document']").Click
Or same thing to target href by its value
ie.document.querySelector("[href*=fsopenWindow]").Click
The last one looks for href containing 'fsopenWindow'
Both of these avoid looping over collections of elements and use CSS so are faster.
In the end I came up with this. Thank you for help Nicholas Kemp, your answer send me to right direction
Set elements = IE.document.getElementsByTagName("a")
For Each element In elements
If Left(element, 33) = "javascript:FSResults_fsopenWindow" Then
Debug.Print element
IE.Navigate element
End If
Next

VBA getelementsbyclassname use with getelementsbyid

I'm trying to write a short VBA code to click on a button on a website by searching first by its classname, and then by id:
Sub Autoclick[enter image description here][1]()
Dim IE As Object
Set IE = CreateObject("InternetExplorer.Application")
IE.Navigate "http://stackoverflow.com/"
IE.Visible = True
While IE.Busy
DoEvents
Wend
IE.Document.getElementsByClassname("nav mainnavs").getElementById("nav-jobs").Click
End Sub
However the code would not click on the Jobs button. I understand that I can just use getelementbyid directly, but I'd still like to know why using getelementsbyclassname and getelementbyid together would not work.
Attached image contains the html code of the website.
Thanks a lot for any help!
I'd still like to know why using getelementsbyclassname and
getelementbyid together would not work.
Because code IE.Document.getElementsByClassname("nav mainnavs").getElementById("nav-jobs") causes error 438: object doesn't support this property or method.
It doesn't work because getElementsByClassName("nav mainnavs") returns a div and divs doesn't have any getElementById method.
To search the div by element id it would probably be necessary to loop through all the elements of it and check their id:
Dim mainnavs
Set mainnavs = IE.document.getElementsByClassName("nav mainnavs")
If mainnavs.Length > 0 Then
Dim mainnavItem ' this is a div element and it doesn't have .getElementById() method
Set mainnavItem = mainnavs.Item(0)
Dim itm
For Each itm In mainnavItem.all
If itm.ID = "nav-jobs" Then
itm.Click
Exit For
End If
Next itm
Else
MsgBox "getElementsByClassName('nav mainnavs') didn't return any elements"
End If
when I apply the same method to my company's website it keeps on
showing the message box "didn't return any elements"
This means that element with such class name does not exist on the page.
Do you wait until the page is fully loaded?
While ie.Busy Or ie.readyState <> READYSTATE_COMPLETE: DoEvents: Wend
why would we do mainnavItem.all in the For loop
This is because there is no other possibility to search for element by its id. Therefore we go through all the children of the mainnavItem and check the id.

VBA and Internet Explorer: fill in an input box

I'm new to making interactions between VBA and Internet Explorer, but I've read many things online and couldn't figure out the problem in my code. I just want to retrieve the 'Username' box on a website and add a value inside. So I retrieved all input boxes into a collection of HTML elements, but then that collection is empty:
Dim Collect As IHTMLElementCollection
With IE
.navigate "http:xxxxxxxxxx"
.Visible = True
End With
Do While IE.Busy
Loop
Set Collect = IE.document.getElementsByTagName("input")
MsgBox Collect.Length
End Sub
This will give a message box with "0". If I toggle a breakpoint before the end of the code and I "watch" the variable Collect, I can see there are 17 items inside, one of them being the username 'inputbox', with name 'tfUserName'. Can you help me please?
EDIT: I found that the problem comes from this code:
Do While IE.Busy
Loop
Which I replaced with this:
Do Until IE.readyState = READYSTATE_COMPLETE
DoEvents
Loop
And now everything works fine. Thank you for your responses.
Validate the collection against null instead to determine if it contains elements
If Not Collect Is Nothing Then
For Each htmlElement In Collect
If Not htmlElement.getAttribute("username") Is Nothing Then
htmlElement.setAttribute("value", "licou6")
Exit For
End If
Next
End If