Interaction With WebPage VBA - html

I'm creating a code that allows me to open a specific site and enter value in element with the name searchByTagName=searchByTRSMP and then Type search to load the new window
But the problem that button search doesn't have a TagName or IdName only this
<td width="13%" align="center" rowSpan="1" colSpan="1">
<input name="" onclick="Javascript:document.forms[0].submit();return false;" type="image" srx="/cmh/cmh/xxxxxx" border="0"></input>
Anyone Can Light me on pressing that button with only those conditions
this Mycode :
Sub ToComb()
Dim ie As Object
Dim itm As IHTMLElement
Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = True
ie.navigate "http://XXXX-
XXXX.eu.airbus.XXXXXp:XXXXX/cmh/consultation/preSearchTRSTDMAS.do?
clearBackList=true&CMH_NO_STORING_fromMenu=true"
While ie.Busy Or ie.readyState <> 4: DoEvents: Wend
Set itm = ie.document.getElementsByName("searchByTRSMP")(0)
If Not itm Is Nothing Then itm.Value = "k20734"
Set Doc = ie.document
Set tags = ie.document.getElementsByTagName("")
For Each tagx In tags
If tagx.Value = "Next" Then
tagx.Click
Exit For
End If
Next
End Sub

GetElementsByTagname mean search for an element by the type of an HTML element (such as, div, p or in your example - input).
You can get all your inputs tags (elements), iterate them and identify the required input, based on it's (for example) srx attribute:
Set tags = ie.Document.GetElementsByTagname("Input")
For Each tagx In tags
If tagx.src= "/cmh/cmh/xxxxxx" Then
tagx.Click
End If
Next
In addition, the final src of the input might changed from the actual code, because you use a relative path. Check the actual src with a MsgBox:
For Each tagx In tags
MsgBox tagx.src
I assume it will be different, such as prefix of http and so on:
If tagx.src = "http://xxxx
xxxx.eu.airbus.xxx:xxxx/cxxx/xxx/image/button_search.gif" Then

Related

Input text to search box on web page and click Search

I am trying to input data from Excel workbook to web pages search field and click search button. A lot of different approaches has been tested with success. Current solution gives 424 Error, Object required. Pointing to:
.Document.getElementById("crmGrid_findCriteria").Value = _
Sheets("Other data").Range("A2").Value
HTML for search field:
<input id="crmGrid_findCriteria" title="Search for records" hintlabelid="crmGrid_findHintText" type="text" class="ms-crm-Dialog-Lookup-QuickFind" maxlength="100" tabindex="0" value="">
HTML for Search button:
<img id="crmGrid_findCriteriaImg" src="/_imgs/imagestrips/transparent_spacer.gif" class="ms-crm-ImageStrip-search " imgbase="/_imgs/search" title="Start search" alt="Start search">
Here is structure:
Here is my VBA (link for CRM system so it is not public):
Sub GoToOpport()
'This will load a webpage in IE
Dim ieappIE As InternetExplorerObject
Dim HWNDSrc As Long
Dim elementsSet AsappIE Object= CreateObject("internetexplorer.application")
Set ie = Nothing With appIE
Set ie = New InternetExplorerMedium
ie.Visible = True
ie.Navigate "https://crm.dynamics.com/main.aspx?area=nav_oppts&etc=3&page=SFA&pageType=EntityList&web=true"
With ie
Do
DoEvents
Loop Until ie.ReadyState = READYSTATE_COMPLETE
End With
ie.Document.getElementById("contentIFrame0").contentDocument.getElementById("crmGrid_findCriteria").Value = "hello"
'Unload IE
Set ieappIE = Nothing
End Sub
Error:
It is in an iframe so you need to access that
ie.document.getElementById("contentIFrame0").contentDocument.getElementById("crmGrid_findCriteria")
You can use js to attempt to assign value
ie.document.parentWindow.execScript "document.getElementById('contentIFrame0').document.getElementById('scrmGrid_findCriteria').value = 'hello';"
You could also try navigating to the src of the iframe
ie.navigate2 ie.document.querySelector("#crmContentPanel").src
While ie.Busy Or ie.readyState < 4: DoEvents: Wend
With ie.document.getElementById("crmGrid_findCriteria")
.focus
.value = "abc"
End With
I'm getting a 301 Moved Permanently status when I send a GET request and then I'm redirected here:
https://dynamics.microsoft.com/en-us/crm/what-is-crm/
The id="crmGrid_findCriteria" is nowhere to be found in the HTML response, so my guess is that if you try:
debug.print ie.Document.getElementById("crmGrid_findCriteria") Is Nothing
you'll get TRUE as a result.
In other words, the element you're looking for doesn't exist in the HTML you downloaded.

Using VBS to select a value on a dropdownlist in webpage

I'm currently working on on a script to open a website, select a value in a dropdownlist and do a search, I'm having trouble with the selection of a value in the dropdownlist, below is my vbs code:
Dim IE
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = 1
IE.navigate "https://website.com/form.aspx"
Do
WScript.Sleep 10
Loop While IE.ReadyState <4 And IE.Busy
'Button to access form
Set SLTOI = IE.document.getElementByID("ctl00_m_g_4e7438b0_6aba_44b0_a0a1_f49486f81665_FormControl0_V1_I1_S1_I1_B1")
SLTOI.click
'Dropdownlist element
Set SPCI = IE.document.getElementByID("ctl00_m_g_4e7438b0_6aba_44b0_a0a1_f49486f81665_FormControl0_V1_I1_S2_I2_D7")
For Each opt In SPCI.options
MsgBox opt.value
If opt.value = "ION CISCO" Then
opt.Selected = True
Else
opt.Selected = False
End If
Next
The source of the dropdownlist is the following (using developers option to inspect the element in IE)
<SELECT tabIndex=0 title="" class="v_utCmzxtdUQZu9e3j_0 n_utCmzxtdUQZu9e3j_0 bb_utCmzxtdUQZu9e3j_0 d3_utCmzxtdUQZu9e3j_0" id=ctl00_m_g_4e7438b0_6aba_44b0_a0a1_f49486f81665_FormControl0_V1_I1_S2_I2_D7 style="DIRECTION: ltr" onfocus="return (DropDownList.OnFocus(this, event));" onblur="return (DropDownList.OnBlur(this, event));" onchange="return (DropDownList.OnChange(this, event));" OriginalId="V1_I1_S2_I2_D7" FormId="ctl00_m_g_4e7438b0_6aba_44b0_a0a1_f49486f81665_FormControl0" ViewDataNode="12" direction="ltr" wrapped="true" ScriptClass="DropDownList"><OPTION value=""></OPTION><OPTION value="ION CISCO" selected>ION CISCO</OPTION></SELECT>
The code executes correctly but the value is not selected in the dropdownlist field (added a Msgbox inside the For to see if the code executed, but it doesnt enter the For at all), if i select a value manually from the list and then try to select another value, the list only has the value i selected previously, unless i click a clear button the list is not populated again, seems that a script is running to populate the list.
Any ideas on how i can make my code work?, have tried to use the "FireEvent("onchange")" after doing a selection but didnt work.
Any help will be appreciated!
What about this? Also, you should declare your IE as an Object rather than a variant
Dim IE As Object
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = 1
IE.navigate "https://website.com/form.aspx"
Do
WScript.Sleep 10
Loop While IE.ReadyState <4 And IE.Busy
'Button to access form
Set SLTOI = IE.document.getElementByID("ctl00_m_g_4e7438b0_6aba_44b0_a0a1_f49486f81665_FormControl0_V1_I1_S1_I1_B1")
SLTOI.click
'Dropdownlist element
Set SPCI = IE.document.getElementByID("ctl00_m_g_4e7438b0_6aba_44b0_a0a1_f49486f81665_FormControl0_V1_I1_S2_I2_D7")
Dim SelectThis as String
SelectThis = "ION CISCO"
SPCI.Value = SelectThis

Get value from web document input element with VBA

I am having difficult to retrieve value 300 from the input named points.
Here's my HTML and VBA code.
HTML:
<td id="myPower_val_9" style="visibility: visible;">
<input type="text" disabled="disabled" value="300" name="points"></input>
</td>
VBA:
Dim ie As Object
Dim myPoints As String
Set ie = CreateObject("InternetExplorer.Application")
With ie
.Visible = 0
.navigate "www.example.com"
While .Busy Or .readyState <> 4
DoEvents
Wend
End With
Dim Doc As HTMLDocument
Set Doc = ie.document
myPoints = Trim(Doc.getElementsByTagName("td")(0).getElementById("myPoints").innerText)
Range("A1").Value = myPoints
HTML Code
I'd try working out the code that manipulates the Document Object Model (DOM) in javascript in a web browser so you can make use of better web based debugging tools.
There are several issues here that a console or debugger could help out with:
You want to get the element ID myPoints but in HTML it's just called points
You want to get the element by ID, but you've only set the name property -
As long as name is unique to the element, you don't need to search for a td first
As you can see from <input></input>, input elements do not have innerText (the text inside the ><). Instead they have a value attribute
The element exposes it's attributes and other data through the properties on the object itself. So you can check the input's value by just looking at .value
Here's a javascript example of what you're trying to do:
var value = document.getElementsByName("points")[0].value;
console.log(value);
<input type="text" disabled="disabled" value="300" name="points" />
Open the console (F12), and you should see 300
VBA
To convert it to VBA code for Excel, just make sure you uses parentheses () for VB arrays instead of square brackets [] for JS arrays:
myPoints = Trim(Doc.getElementsByName("points")(0).Value)
That should work just fine.
References
Since I'm not sure at what point you're failing in VB, also make sure you have all the proper web references in place in your VBA script.
Go to Tools > References > and add "Microsoft HTML Object Library" and "Microsoft Internet Controls":
Demo
I created a demo in plunker so there would be a live site to go against instead of example.com.
Paste the following code into excel and everything should work fine:
Public Sub GetValueFromBrowser()
Dim ie As Object
Dim url As String
Dim myPoints As String
url = "http://run.plnkr.co/plunks/6UTb9kHRZ363Ivhh2BPE/"
Set ie = CreateObject("InternetExplorer.Application")
With ie
.Visible = 0
.navigate url
While .Busy Or .readyState <> 4
DoEvents
Wend
End With
Dim Doc As HTMLDocument
Set Doc = ie.document
myPoints = Trim(Doc.getElementsByName("points")(0).Value)
Range("A1").Value = myPoints
End Sub
Output:
CSS selector:
Use a CSS selector to get the element of input[name='points']
You don't show enough HTML to know if this is the only on the page. The above says elements with input tag having attribute name whose value is 'points'
CSS query:
VBA:
You apply the CSS selector with .querySelector method of document for a single element; .querySelectorAll for a nodeList of all matching elements i.e. if there is more than one on the page and you get the one of interest by index.
Debug.Print ie.document.querySelector("input[name='points']").getAttribute("value")
You need to use .getAttribute("name of attribute") to get an attributes value. In your case .getAttribute("value") will return 300.
Dim ie As Object
Dim myPoints As String
Set ie = CreateObject("InternetExplorer.Application")
With ie
.Visible = 1
.navigate "website URL"
While .Busy Or .readyState <> 4
DoEvents
Wend
End With
Dim Doc As HTMLDocument
Set Doc = ie.document
myPoints = Trim(Doc.getElementsByTagName("td")(0).getElementsByTagName("input")(0).getAttribute("value"))
Range("A1").Value = myPoints
Just on a side note. I don't know much about HTML and maybe someone can elaborate on this more. But if you want to test that HTML code you need to add in the < table> < tr> tags.
Something like this:
<table>
<tr>
<td id="myPower_val_9" style="visibility: visible;">
<input type="text" disabled="disabled" value="300" name="points"></input>
</td>
</tr>
</table>

HTML object library / pull

I have the following code in an HTML web page, and I am trying to use the html object library via vba engine to pull the value from within this tag:
<input name="txtAdd_Line1" disabled="disabled" size="30" maxLength="50" value="123 N 1ST ST"/>
I figure I have to use .getelementsbytagname or .getelementsbyname, but I am not sure how to grab the value. Does anyone have any ideas?
Here's an example with comments, subtitute in your actual address:
Sub Example()
'Declare needed variables
Dim ie, elements
Dim x As Long
'Create IE Applction
Set ie = CreateObject("InternetExplorer.Application")
'Navigate to the website
ie.navigate "C:\test.html" 'Substitute your actual address
'Wait for website to finish loading
Do While ie.ReadyState <> 4
Loop
'Find the elements
Set elements = ie.document.getelementsbyName("txtAdd_Line1")
'Display the value of each returned element
For x = 0 To elements.Length - 1
MsgBox elements(x).Value
Next
'Quit IE
ie.Quit
End Sub
Based on your comment most likely just looking at the document wasn't retrieving the actual layer of the tree you wanted, try this:
Set HTMLDoc = ie.document.frames("MainFrame").document
With HTMLDoc
'This returns an (object) which contains an array of all matching elements
a = .getElementsByName("txtAdd_Line1")
end with
For x = 0 to a.length
msgbox a(x).value
next
You can use a CSS selector of input[name='txtAdd_Line1'] . This says element with input tag having attribute name with value 'txtAdd_Line1'.
CSS selector:
You apply a CSS selector using the .querySelector method of document e.g.
Msgbox ie.document.querySelector("input[name='txtAdd_Line1']").innerText

Fill in website search bar using Excel VBA

I'm trying to make an Excel macro that inserts data into a web search form and then copies the results into a table. The web search form is not actually a "form", but a blank table so I can't just change the input value of the form because there is none:
<td valign="top">
<table border="0" cellspacing="0" cellpadding="2">
<tr>
<th class="navLabelText" align="left">Order:</th>
<td>
<input class="navEditField" id="opt_ordernumber_int" name="ordernumber" type="text" size="6" maxlength="6" />
</td>
</tr>
</table>
</td>
<td width="10"> </td>
The HTML just continues with more of the same types of forms (I'm guessing coded in Java since the site is a .jsp). Is there any way that I can pass values into the blank table?
Here's what I have so far:
Sub featurecode()
Dim ie As Object
Dim doc As HTMLDocument
Dim links As IHTMLElementCollection
Dim link As HTMLAnchorElement
Dim i As Integer
Dim found As Boolean
Dim todaysURL As String
Dim objElement As Object
Dim objCollection As Object
Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = True 'false
ie.navigate "https://website.com"
Application.StatusBar = "Loading Feature Codes"
Do Until ie.readyState = IE_READYSTATE.complete: DoEvents: Loop
Set doc = ie.document
' Find the input tag of the order form and submit button:
Set objCollection = ie.document.getElementsByTagName("input")
i = 0
While i < objCollection.Length
If objCollection(i).Name = "ordernumber" Then
' Set text for search
objCollection(i).Value = "655032"
Else
If objCollection(i).Type = "submit" And objCollection(i).Name = "Submit" Then
' "Search" button is found
Set objElement = objCollection(i)
objElement.Click
End If
End If
i = i + 1
Wend
End Sub
The part that I'm having trouble with is this:
If objCollection(i).Name = "ordernumber" Then
' Set text for search
objCollection(i).Value = "655032"
Usually you can change the HTML value of the form, but in this case there is no HTML value in the input tag, so I'm at a loss. My goal here is to simply insert an order number into the form and hit the submit button. Unfortunately I can't show you the website as it's an internal corporate site, but here's a screenshot of the relevant info: screenshot
Thanks!
I've found with some elements in VBA, including INPUT, you have to focus on the element first:
objCollection(i).Focus
objCollection(i).Value = "655032"