VBA HTML Object Internet Explorer automation - html

How do I select an option from a dropdown menu and update the webpage.
Code:
Dim IE As New SHDocVw.InternetExplorer
Dim HTMLDoc As MSHTML.HTMLDocument
then I navigate to a URL and I fetch the dropdown menu using html id and put value=my desired value
HTMLDoc.getElementById("xyz").Value = "dropdown_option"
I successfully get the option. But, the website doesn't update? e.g. filling up other fields.
I believe some javascript needs to be run.
How can i fix this using VBA?
Source code for dropdown menu field:
<div id="ctl00_MainContent_CreateWebForm__SubjectComboBox_ComboBox" class="Invalid RadComboBox RadComboBox_Telerik SearchComboBox" style="width:206px;white-space:normal;">
<table summary="combobox" style="border-width:0;border-collapse:collapse;width:100%" class="rcbFocused rcbExpanded">
<tbody><tr class="rcbReadOnly">
<td class="rcbInputCell rcbInputCellLeft" style="width:100%;"><input name="ctl00$MainContent$CreateWebForm_$SubjectComboBox$ComboBox" type="text" class="rcbInput radPreventDecorate" id="ctl00_MainContent_CreateWebForm__SubjectComboBox_ComboBox_Input" value="Vælg" readonly="readonly" accesskey="s" autocomplete="off"></td><td class="rcbArrowCell rcbArrowCellRight"><a id="ctl00_MainContent_CreateWebForm__SubjectComboBox_ComboBox_Arrow" style="overflow: hidden;display: block;position: relative;outline: none;">select</a></td>
</tr>
</tbody></table><input id="ctl00_MainContent_CreateWebForm__SubjectComboBox_ComboBox_ClientState" name="ctl00_MainContent_CreateWebForm__SubjectComboBox_ComboBox_ClientState" type="hidden" autocomplete="off">
</div>
Source code for dropdown options:
<div id="ctl00_MainContent_CreateWebForm__SubjectComboBox_ComboBox_DropDown" class="RadComboBoxDropDown RadComboBoxDropDown_Telerik " style="width: 204px; display: block; top: 0px; visibility: visible; transition: none 0s ease 0s;">
<div class="rcbScroll rcbWidth" style="height: 126px;">
<ul class="rcbList"><li class="rcbHovered">Forespørgsel til Energinet</li>
<li class="rcbItem">Måledata</li><li class="rcbItem">Målepunkt eller ad hoc spørgsmål</li>
<li class="rcbItem">Orientering til alle</li>
<li class="rcbItem">Priser</li><li class="rcbItem">Pristilknytninger</li></ul></div></div>

For anyone stuck with this issue. I solved this by finding focus property of getelementbyid method. Like this:
First I loop over the list to find my option. I use tagname and classname and matching the innertext property = myoption (This is only necessary if the field doesn't allow you to input text) Then when match occurs, perform .focus followed by .click on that object.
Otherwise just use focus followed by click property on the field and enter your option:
HTMLDoc.getElementById("xyz").focus
HTMLDoc.getElementById("xyz").click
HTMLDoc.getElementById("xyz").Value = myoption
This will automatically refresh the html page.
This solved my issues.

Related

Excel VBA to click HTML element from a list in a table

I know there have been similar questions on SO about this issue, and I have been reviewing and trying many of them, but still, I'm having an issue selecting an option from a drop-down list on a website. I'm really trying to figure this out on my own, but I can't seem to get this part right.
Unfortunately, the website can only be accessed internally (of course!), so I can't share it, but I've tried to provide the HTML that I think is relevant.
What I'm trying to do is select the "Equals To" option from the list. Most of my attempts end up skipping the IF = Equals To part and advances to the next part of the VBA.
Here are a couple of my more recent attempts. (Getting an Object Required error on the QuerySelector approaches.
<!DOCTYPE html>
<html>
<body class="bootstrap-wrapper" style="cursor: auto;">
<div tabindex="-1" class="ui-dialog ui-corner-all ui-widget ui-widget-content ui-front dialog ui-draggable ui-resizable" role="dialog" aria-describedby="02T" aria-labelledby="ui-id-1" style="left: 328px; top: 167.5px; width: 977px; height: 603px; overflow: visible; display: block; position: absolute; z-index: 201;">
<div title="" class="chosen-container chosen-container-single chosen-container-single-nosearch chosen-with-drop chosen-container-active" id="paymentReferenceNumber_chosen" style="left: 482px; top: 279.41px; width: 200px; margin-top: 45px; margin-left: 0px; position: absolute;">
<div class="chosen-drop" style="display: block;">
<div class="chosen-search"><input type="text" readonly="" autocomplete="off"></div>
<ul class="chosen-results">
<li class="active-result result-selected" data-option-array-index="0">
Select
</li>
<li class="active-result" data-option-array-index="1">
Equals To
</li>
<li class="active-result" data-option-array-index="2">
Contains
</li>
<li class="active-result" data-option-array-index="3">
Is Empty
</li>
</ul>
</div>
</div>
</div>
</body>
</html>
Dim inputElement As HTMLInputElement
Set inputElement = doc.querySelector( _
"html body[class=bootstrap_wrapper] tbody div[tabindex=-1] div[class=chosen-container chosen-container-single chosen-container-single-nosearch chosen-with-drop chosen-container-active] div[class=chosen-drop] ul[class=chosen-results] li[class=active-result][data-option-array-index=1]")
If Not inputElement Is Nothing Then
inputElement.Click
End If
OR
ieApp.Document.querySelector("Select[name=paymentReferenceNumber_oper] option[value=equalsTo]").Selected = True
OR
Set ElementCol = ieApp.Document.getElementsByTagName("li")
For Each ee In ElementCol
If ee.innerHTML = "Equals To" Then
ee.Click: DoEvents: Sleep 1000
Exit For
End If
Next ee
Most of the other links I have been able to select simply by using:
ieApp.Document.all.Item("adv_search_tab").Click: Sleep 1000
Or Using:
Set ElementCol = ieApp.Document.getElementsByTagName("input")
For Each ee In ElementCol
If ee.Name = "search" Then
ee.Click: DoEvents: Sleep 1000
Exit For
End If
Next ee
These are just two of the recent SO posts I have been reviewing to try to understand alternatives:
VBA selecting a value from dropdown box on a webpage
Excel VBA change option in the HTML select tag

Not sure what element I need to click in IE HTML for VBA?

So I have the following HTML code (I'm not super familiar with HTML so excuse the incorrect spacing):
<div class="section_heading">
<span class="section_anchor" id="ajax_result_table_link" data-label="vs. Pitchers"></span>
<h2>vs. Pitchers</h2>
<div class="section_heading_text">
<ul>
<i>Sorting only sorts the values in the table shown</li>
<li>Click a player to see each PA</li>
<li class="hasmore drophover">
<span href="javascript:void(0)">Share & more</span>
<div>
<div class="closer" role="button" aria-label="close this menu"></div>
<ul>
<li><button class="tooltip" id="share_on_ajax_result_table" tip="Use a customizable report creator that can<br>output HTML, CSV, or a shareable link.">Modify & Share Table</button>
</li>
<li><button class="tooltip" tip="Get a bit of widget code to emed this table on your site">Embed this Table</button></li>
<li><button class="tooltip" tip="Convert the table below to comma-separated values<br>suitable for use with excel">Get as Excel Workbook (experimental)</button><a id="dlink" style="display: none;"></a></li>
<li><button class="tooltip" tip="Export table as <br>suitable for use with excel">Get table as CSV (for Excel)</button></li><li><button class="tooltip" tip="">Strip Mobile Formatting</button></li>
From this URL: https://www.baseball-reference.com/play-index/batter_vs_pitcher.cgi?batter=mancitr01
I am trying to use VBA to download the Excel workbook (under the "Share & More" Dropdown), but I can't seem to be able to click the link. I've tried using get element by class and get element by ID but they don't seem to work. I'm guessing this HTML code is a little more advanced than I'm used to. I've been trying to click the ID "dlink" but I'm not sure if that is the end goal.
Any help or input would be appreciated.
EDIT:
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim IE As Object
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
IE.Navigate "https://www.baseball-reference.com/play-index/batter_vs_pitcher.cgi?batter=mancitr01"
Wait 10
IE.document.getElementById("dlink").Click
Exit Sub
Set oElementCollection = IE.document.getElementsByClassName("section_heading_text")
For Each span In oElementCollection
If span.innerHTML = "Share & more" Then
span.ParentNode.Click
Exit For
End If
Next span
Exit Sub

Doubts in clicking Unordered List in IE using VBA

I have an unordered list with links in IE and the list is also dynamic. Clicking on the 1st level in the list will open the 2nd level and so on. My work is to select one link within 4th level. So I have to click upto 4th level and click another option after that.
Initially, without clicking anything, the html code of the list will be,
<div class="tree" id="treeDiv" style="width: 288px; border-top-color: transparent; border-top-width: 195px; border-top-style: solid;" ondragstart="return false" onselectstart="return false" oncontextmenu="return false">
<ul style="width: 915px;">
<li>
<a class=" open" id="level1st" onclick="resetTree(0);" href="#">GENERAL </a>
<ul></ul>
</li>
</ul>
</div>
After clicking "GENERAL" (1st level), the html code of the list will be,
<div class="tree" id="treeDiv" style="width: 288px; border-top-color: transparent; border-top-width: 195px; border-top-style: solid;" ondragstart="return false" onselectstart="return false" oncontextmenu="return false">
<ul style="width: 915px;">
<li>
<a class=" open" id="level1st" onclick="resetTree(0);" href="#">GENERAL </a>
<ul>
<li>
<a class=" open" id="0/2" style="padding-left: 13px;" href="#">GENERAL </a>
<ul></ul>
</li>
</ul>
</ul>
</div>
To click 1st level, I tried writing two kinds of codes,
CODE 1-----
Sub A()
Dim ie As InternetExplorerMedium
Dim availableLinks As MSHTML.HTMLElementCollection
Dim cLinks As MSHTML.HTMLLIElement
Set ie = New InternetExplorerMedium
ie.Navigate 'URL
Do While ie.readyState <> READYSTATE_COMPLETE
DoEvents
Loop
Set availableLinks = ie.document.getElementsByClassName("tree").getElementsByTagName("li")
For Each cLinks in availableLinks
If cLinks.innerText = "General" Then
cLinks.click
End If
Next cLinks
End Sub
CODE 2-----
Sub B()
Dim ie As InternetExplorerMedium
Dim availableLinks As MSHTML.HTMLElementCollection
Dim cLinks As MSHTML.HTMLLIElement
Set ie = New InternetExplorerMedium
ie.Navigate 'URL
Do While ie.readyState <> READYSTATE_COMPLETE
DoEvents
Loop
Set availableLinks = ie.document.getElementsByClassName("tree").getElementsByTagName("a")
For Each cLinks in availableLinks
If cLinks.ID = "level1st" Then
cLinks.Focus
cLinks.FireEvent("onclick")
End If
Next cLinks
End Sub
Now about my doubts,
Assuming my CODE 1 is correct, I am able to select my 1st level thro' innerText 'General'. But my 2nd level also has the same innerText 'General'. So how do I specify in code that it is the 2nd level.
Also, in CODE 1, I have used cLinks.click. Is it correct or should I use cLinks.FireEvent("onclick")?
Now in CODE 2, I have declared cLinks As MSHTML.HTMLLIElement. But I am not using any <li> tag in the code. So what should I declare it as, as MSHTML.HTMLLIElement or as MSHTML.HTMLElement?
Finally, is CODE 1 and CODE 2 correct pertaining to my unordered list? I cannot execute my code and check now as I have to go to my office to do that.
So what do you think? Which one is suitable? I think CODE 2 would be appropriate for all the levels.
If both the codes are wrong, can you suggest a suitable one?
Sorry for the very long post, I am just learning web-scraping so I am full of doubts for which I am not able to find solutions in internet.
Can anyone please help? Thanks in advance.

Click the second button of an img in VBA

I'm trying to click an imagebutton on IE by using getAttribute("src"), but there are to identical buttons with the same src-code, so when I use this code, it clicks the first and I want to click the second. Can somebody help me?
I'm thinking of creating a loop to search through and choose the second one, but I have no idea how to write the code! Can somebody help me out?
This is the code I use to click the first button:
Set allInputs = IE.Document.getElementsByTagName("img")
For Each Element In allInputs
If Element.getAttribute("src") = "/forms/Content/Images/0006.gif" Then
Element.Click
Exit For
End If
Next Element
The HTML code for the buttons are:
<tr class="jqgfirstrow" role="row"
<tr tabindex="-1" class="ui-widget-content jqgrow ui-row-ltr" id="1" role="row"
< img src="/forms/Content/Images/0006.gif"
<tr tabindex="-1" class="ui-widget-content jqgrow ui-row-ltr" id="2" role="row
< img src="/forms/Content/Images/0006.gif"
Thanks for all of your help!
I did it with code here:
Set allInputs = IE.Document.getElementsByTagName("img")
allInputs(2).click

get element id with vb

I have the following code in an aspx page:
<div id="objectList" style="overflow: auto; width:100px; display:block;
position:absolute;top:0px;left:0px;z-index:100;">
<div id="object8" class="object" title="">
<br>object8</div>
<div id="object2" class="objectSelect" title="">
<br>object2</div>
</div>
I am attempting to find the ID of the object that is selected, in this case object2. I am trying to do it in the codebehind with vb.net but I'm not sure how. Any help would be appreciated.
Add runat="server" to all of the <div> elements you wish to find out if they are selected or not, like this:
<div id="object8" class="object" title="" runat="server">
<div id="object2" class="objectSelect" title="" runat="server">
Now in code-behind you can loop through all of the <div> elements in the page and check the class attribute value, like this:
For Each item As Control In Me.Controls
' We have to look at all HtmlGenericControl, because
' there is no .NET control type for DIV
Dim theDiv As System.Web.UI.HtmlControls.HtmlGenericControl = TryCast(item, System.Web.UI.HtmlControls.HtmlGenericControl)
' Make sure the cast worked before we try to use the DIV
If theDiv IsNot Nothing Then
' Is the class name equal to objectSelect?
If theDiv.Attributes("class") = "objectSelect" Then
' Yes, this DIV is selected, do something here
End If
End If
Next