Automate Internet Explorer: enter a value that has no "ID" - html

I'm trying to use excel VBA to automate the data entering on a intranet Webpage of my company. I know how to interact with values of a web page the fields have "id" like in the html code below
<input name="txtUserName" tabindex="1" id="txtUserName" type="text">
With that kind of html code I would use something like
IE.Document.getElementbyId("txtUserName").Value = "UserName"
The problem I'm facing is that the code associated with the field I'm trying to interact is
<HTML><HEAD><META content="IE=5.0000" http-equiv="X-UA-Compatible">
<SCRIPT type=text/javascript>
function ajusterFrames() {
var iLargeurGauche = 217;
var iLargeurDroite = 850;
var iLargeurFenetre = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var iMarge = 0;
var sCols = "";
if (iLargeurFenetre > (iLargeurGauche + iLargeurDroite)) {
iMarge = (iLargeurFenetre - (iLargeurGauche + iLargeurDroite)) / 2;}
sCols = (iLargeurGauche + iMarge) + ",*";
document.getElementById("framesetbas").cols = sCols;
document.getElementById("cadres").style.display = "block";}
window.onload = ajusterFrames;
window.onresize = ajusterFrames;
</SCRIPT>
<TBODY>
<TR> </TR>
<TR>
<TD>
<!--RECHERCHE-->
DIV id=Projet>
<!--RECHERCHE-->
<CENTER>
<FIELDSET style="WIDTH: 600px" name="recherche">
<LEGEND style="FONT-SIZE: 10px; FONT-FAMILY: verdana; COLOR: #767676" name="legende_recherche">
<INPUT onclick=afficherRecherche(this.value); type=radio value=simple name=TypeRecherche>
</DIV><!------RECHERCHE AVANCÉE------------------------------------->
<DIV id=divAvancee>
<CENTER>
<TABLE cellSpacing=0 cellPadding=0 border=0>
<TBODY>
<TR>
<TR>
<TR>
<TR>
<TR>
<TR>
<TD align=right>
<FONT color=#003366 size=1 face=verdana>No Projet :</FONT></TD>
So I'm trying to modify the value of the field identify by: "txtNoProjet" Here's the code I could come up with, I tried many versions around this and still can't get it right.
UPDATED CODE TO INCLUDE SOLUTION
Private Sub entree_budget()
Dim i As Long
Dim IE As Object
Dim Doc As Object
Dim objElement As Object
Dim objCollection As Object
Dim buttonCollection As Object
Dim valeur_heure As Object
num_proj = Cells(1, 3) 'this is the value that I need to input
' 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://intranet.cima.ca/fr/application/paq/projets/index.asp?v1_lang=1"
' Wait while IE loading...
Do While IE.Busy
Application.Wait DateAdd("s", 1, Now)
Loop
'UPDATED CODE BELOW
Set links = IE.Document.frames(2).Document.getElementsByTagName("input")
n = links.Length
While i < n
If links(i).Name = "txtMotCle" Then
links(i).Value = num_proj
End If
i = i+ 1
Wend
End Sub
Can anyone help me with this?
And also if I may I will the need to click the button "search" on the bottom of the form , but I can't recognize it's syntax so I don't know how to interact with it. Could someone tell me how to click the button that has this html code?
<A href="javascript:submitForm('avancee');">
<IMG border=0 alt="Rechercher un projet" src="../../../images/fr/rechercher.gif"></A>
UPDATED CODE SOLUTION FOR THIS IS:
Set links = IE.Document.frames(2).Document.getElementsByTagName("a")
n = links.LengtH
i = 0
While i < n
If links(i).href = "javascript:submitForm('avancee');" Then
Set objElement = links(i)
objElement.ClicK
End If
i = i + 1
Wend
Thank you so much in advance for the time you'll spend answering my questions.

Edited: the input elements were contained in a frame, which is why #jeeped's answer wasn't working. getElementsByTagName("input") should have returned them. Hopefully this edit will save you from having to read through the comments to find that out. To return inputs contained in a frame, use
IE.document.frames(x).document.getElementsByTagName("input")
where x is the index of the frame.
Original response below.
=======================================================
If it's zero-based, shouldn't you remove the -1 that's preventing the loop from running? That is, if there is one element, then the for loop would be iNPT = 0 to 0 and execute once. If there were two, then the .length would return 1 and =0 to 1 would execute twice, as expected.
I personally would probably include both Microsoft Internet Controls and Microsoft HTML Object Library in the references for the project so that I could use early binding and declare the variables, and then use a for each to iterate:
Dim inputs As MSHTML.IHTMLElementCollection
Dim inpt As MSHTML.IHTMLInputElement
Dim IE As New SHDocVw.InternetExplorer
IE.Visible = True
IE.navigate "http://intranet.cima.ca/fr/application/paq/projets/index.asp?v1_lang=1"
While IE.readyState <> READYSTATE_COMPLETE: DoEvents: Wend
Set inputs = IE.document.getElementsByTagName("input")
For Each inpt In inputs
If inpt.Name = "txtNoProjet" Then inpt.Value = num_proj
Next
Be aware that the HTML Object Library includes several different IHTMLElementCollections, with different numbers. In some situations you might need to use one of those instead. Also, you may need to use getAttribute to access the attribute:
If inpt.getAttribute("name") = "txtNoProjet" then inpt.Value = num_proj

The index to a collection of elements is zero-based. Assuming that there is only a single txtNoProjet you would use,
IE.Document.getElementsbyName("txtNoProjet")(0).Value = num_proj
I've had trouble with .getElementsbyName in the past. If the above does not work for you, collect all of the <input> elements and cycle through them until you find the one you want.
dim iNPT as long
for iNPT=0 to (IE.Document.getElementsbyTagName("input").length - 1)
if IE.Document.getElementsbyTagName("input")(iNPT).name = "txtNoProjet" then
IE.Document.getElementsbyTagName("input")(iNPT).value = num_proj
exit for
end if
next iNPT
One of those should get you going. The biggest problem you will run into would be duplicate names.
EDIT: addendum for clicking an image anchor
dim iIMG as long
for iIMG=0 to (IE.Document.getElementsbyTagName("img").length - 1)
if CBool(InStr(1, IE.Document.getElementsbyTagName("img")(iIMG).src, "rechercher.gif", vbTextCompare)) then
IE.Document.getElementsbyTagName("img")(iIMG).click
do while IE.Busy Or IE.ReadyState <> READYSTATE_COMPLETE: Do Events: Loop
exit for
end if
next iIMG
I usually prefer something closer to IE.Document.getElementsbyTagName("form")(0).submit but you haven't provided enough HTML source code to write that properly. You will have to adjust that code to look into your .Frames element.

Related

VBA error when triggering "change" event on IE input field

I'm trying to use VBA to access an internal web page using Internet Explorer, open a search window, enter search parameters and run the search. My code will click all of the buttons, find all of the text boxes and enter the parameters. But, it does not recognize any of the parameters entered using ".value" (i.e., objElement.value = "1234567"). I have written the code based on what I have read in this forum and a number of others but, obviously, I'm still missing something. When it tries to trigger the "change" event, I receive either an Error 438 - Object Doesn't Support this Property or Method, or an Error 5 - Invalid Procedure Call or Argument. The error depends on whether I use dispatchEvent or FireEvent and whether I use the collection or the element within the collection as the object. My guess is the problem lies with my declarations but, I tried a few different ones, and still get the errors.
Unfortunately, this is accessing an internal site so you won't be able to run the code. I'm hoping someone can just take a look and point me in the right direction.
Dim EPA As String
Dim EPANumb As Integer
Dim EPAList() As String
Dim PrjCnt As Long
Dim PrjList As String
Dim WS As Worksheet
Dim IE As InternetExplorerMedium
Dim URL As String
Dim HWNDSrc As Long
Dim objCollection As Object
Dim objElement As Object
Dim objEvent As Object
Dim oHtml As HTMLDocument
Dim HTMLtags As IHTMLElementCollection
'Pull list of project numbers and enter into array
fn = ThisWorkbook.Name
EPANumb = WorksheetFunction.CountA(Worksheets("Instructions").Range("B:B"))
EPANumb = EPANumb - 2
ReDim EPAList(EPANumb)
For PrjCnt = 0 To EPANumb
If EPANumb > 0 Then
EPAList(PrjCnt) = "'" & Worksheets("Instructions").Cells((PrjCnt + 2), 2).Value & "'"
Else
EPAList(PrjCnt) = Worksheets("Instructions").Cells((PrjCnt + 2), 2).Value
End If
Next
PrjList = Join(EPAList, ",")
'Open IE and navigate to URL
Set IE = New InternetExplorerMedium
IE.Visible = True 'only if you want to see what is happening
URL = "http://anysite/SnakeEyes/grid.html"
IE.navigate URL
'need If statement in case user needs to do sign on.
' Statusbar let's user know website is loading
Application.StatusBar = URL & " is loading. Please wait..."
'IE ReadyState = 4 signifies the webpage has loaded (the first loop is set to avoid inadvertently skipping over the second loop)
Do While IE.Busy = True Or IE.ReadyState <> 4: DoEvents: Loop
Application.Wait (Now + TimeValue("0:00:05"))
'Webpage Loaded
Application.StatusBar = URL & " loaded"
Set oHtml = IE.document
'HWNDScr = IE.HWND
'SetForegroundWindow HWNDScr
'Open search box and reset search parameters
oHtml.getElementById("search_grid_c_top").Click
'IE.Document.getElementById("fbox_grid_c_reset").Click
Set objEvent = oHtml.createEvent("HTMLEvents")
objEvent.initEvent "change", True, False ' **** NEW ****
Set HTMLtags = oHtml.getElementsByTagName("select")
For i = 0 To HTMLtags.Length - 1
If HTMLtags(i).className = "selectopts" Then
If EPANumb > 0 Then
HTMLtags(i).Value = "in"
Else
HTMLtags(i).Value = "eq"
End If
' HTMLtags.dispatchEvent objEvent ' **** NEW ****
Exit For
End If
Next i
Set objEvent = oHtml.createEvent("HTMLEvents")
objEvent.initEvent "change", True, False ' **** NEW ****
Set HTMLtags = oHtml.getElementsByTagName("input")
For i = 1 To HTMLtags.Length - 1
If HTMLtags(i).ID > "jqg" And HTMLtags(i).ID < "jqh" Then
HTMLtags(i).Focus
HTMLtags(i).Value = PrjList
Exit For
End If
Next i
HTMLtags(i).dispatchEvent objEvent ' **** NEW ****
'HTMLtags(i).FireEvent objEvent ' **** NEW **** DispatchEvent gives an error 438.
'FireEvent gives an error 5 if using the (i); error 438 without it.
HTML Code
Will the "change" event trigger the update for both without VBA in IE? If the "change" event is only associated with the input box and will not trigger update for dropdown list without VBA, then I think it won't work with VBA either. Besides, what the "change" event is like?
I make a demo like below and it seems that the "change" event can be triggered well, you could try to check it.
HTML code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<table>
<tbody>
<tr>
<td class="operators">
<select class="selectopts">
<option value="eq">equal</option>
<option value="in">is in</option>
<option value="ni">is not in</option>
</select>
</td>
<td class="data">
<input class="input-elm" id="jqg1" role="textbox" type="text" size="10" value="'1006191'"/>
</td>
</tr>
</tbody>
</table>
<script>
var select = document.getElementsByClassName('selectopts')(0);
var input = document.getElementById('jqg1');
input.addEventListener('change', updateValue);
function updateValue() {
select.value = "in";
}
</script>
</body>
</html>
VBA code:
Sub LOADIE()
Set ieA = CreateObject("InternetExplorer.Application")
ieA.Visible = True
ieA.navigate "http://somewebsite"
Do Until ieA.readyState = 4
DoEvents
Loop
Set doc = ieA.Document
Set Search = doc.getElementByID("jqg1")
Search.Value = "VBA"
Dim event_onChange As Object
Set event_onChange = ieA.Document.createEvent("HTMLEvents")
event_onChange.initEvent "change", True, False
Search.dispatchEvent event_onChange
'ieA.Quit
'Set ieA = Nothing
End Sub

Selecting a HTML button in Excel VBA that does not have an id

Been working on this issue for a day now. I have a webform that you have 1 set of standard data, and then you enter line items for a purchase requisition; I am trying to enter all data in Excel and use VBA to transfer it to the site. I am getting stuck at how to "update part" (the text on the button that I need to click to add another line item on the webpage). I have also tried the send key method to Shift Tab into the correct location (just normal shifting runs into an error with one of the fields). I am fine with any solution working, this is my first attempt at linking Excel to HTML so it's been fun.
From what I can find the button does not have an id so I have not been successful in calling it.
Here is my code (with the web url deleted):
Sub Login_2_Website()
Dim oHTML_Element As IHTMLElement
Dim oHTML_Element1 As IHTMLElement
Dim sURL As String
Dim aURL As String
Dim nodeList As Object
On Error GoTo Err_Clear
sURL = URL Can't be Shared
oBrowser.Silent = True
oBrowser.timeout = 60
oBrowser.Navigate sURL
oBrowser.Visible = True
Do
' Wait till the Browser is loaded
Loop Until oBrowser.ReadyState = READYSTATE_COMPLETE
Set HTMLDoc = oBrowser.Document
Set nodeList = HTMLDoc.querySelectorAll("a[onlick*='UpdatePartRow']")
HTMLDoc.all.UserName.Value = ThisWorkbook.Sheets("sheet1").Range("I1")
HTMLDoc.all.Password.Value = ThisWorkbook.Sheets("sheet1").Range("I2")
For Each oHTML_Element In HTMLDoc.getElementsByTagName("input")
If oHTML_Element.Type = "submit" Then oHTML_Element.Click: Exit For
HTMLDoc.all.reason.Value = ThisWorkbook.Sheets("sheet1").Range("B1") ' selects the reason for the requisition
HTMLDoc.all.Comments.Value = ThisWorkbook.Sheets("sheet1").Range("B2") ' selects the comments to purchasing
HTMLDoc.forms("_PurchaseRequisition").getElementsByTagName("select")("RequiredMonth").Value = ThisWorkbook.Sheets("sheet1").Range("B3")
HTMLDoc.forms("_PurchaseRequisition").FireEvent ("onchange")
HTMLDoc.forms("_PurchaseRequisition").getElementsByTagName("select")("RequiredDay").Value = ThisWorkbook.Sheets("sheet1").Range("B4")
HTMLDoc.forms("_PurchaseRequisition").FireEvent ("onchange")
HTMLDoc.forms("_PurchaseRequisition").getElementsByTagName("select")("RequiredYear").Value = ThisWorkbook.Sheets("sheet1").Range("B5")
HTMLDoc.forms("_PurchaseRequisition").FireEvent ("onchange")
HTMLDoc.forms("_PurchaseRequisition").getElementsByTagName("select")("CommodityMain").Value = ThisWorkbook.Sheets("sheet1").Range("B9")
HTMLDoc.forms("_PurchaseRequisition").FireEvent ("onchange") 'Selects the commodity group
HTMLDoc.all.Quantity.Value = ThisWorkbook.Sheets("sheet1").Range("B11")
HTMLDoc.all.Description.Value = ThisWorkbook.Sheets("sheet1").Range("B12")
HTMLDoc.all.ChargedDepartment.Value = ThisWorkbook.Sheets("sheet1").Range("B13")
HTMLDoc.all.SubJobNumber.Value = ThisWorkbook.Sheets("sheet1").Range("B14")
HTMLDoc.all.AccountNumber.Value = ThisWorkbook.Sheets("sheet1").Range("B15")
HTMLDoc.all.UnitPrice.Value = ThisWorkbook.Sheets("sheet1").Range("B16")
HTMLDoc.all.CommodityMainSub.Value = ThisWorkbook.Sheets("sheet1").Range("B17")
Set nodeList = HTMLDoc.querySelectorAll("a[onlick*='UpdatePartRow']")
nodeList.Item(0).Click
nodeList.Item(0).FireEvent "onclick"
Next
' oBrowser.Refresh ' Refresh If Needed
Err_Clear:
If Err <> 0 Then
Err.Clear
Resume Next
End If
End Sub
For the login portion I modified code from: http://vbadud.blogspot.com/2009/08/how-to-login-to-website-using-vba.html#ZiqYAtAQMHzl7x1k.99
That works perfectly, so does entering the fields.
The segment of HTML that is associated with this button is:
<a onclick="UpdatePartRow();
chkKeepSubmitPR();
return false;" href=""></a>
<a onclick="var doc = window.document.forms[0];
UpdatePartRow();
chkKeepSubmitPR();
if (doc.OrgMatrixYes.value == "Y") {
VerifyDeptOrgMatrix();
}
return false;" href=""><img src="/Web/purchreq.nsf/UpdatePart.gif?OpenImageResource" width="72" height="25" border="0"></a>
I am taking this on because this system is a pain. I could just have multiple macros and have the user hit the button between each line item, but I want to try to offer a full solution. I am a mechanical engineer by trade and my coding experience is limited to what I have picked up on making tools to ease my job. Any help or suggestions would be super helpful. If there is more info needed, please let me know and I can try to help anyway I can. Thank you!
Update: I have tried (See Code) to make the changes that have been suggested. I am still a fairly complete newbie when it comes to coding, so please bear with me and thank you for trying to teach me!
You have two a tag elements there with an onclick
You can get both with attribute = value CSS selector using "*" contains operator to search for a substring in the attribute value
a[onclick*='UpdatePartRow']
You can grab both with querySelectorAll method of HTMLDocument object
Dim nodeList As Object
Set nodeList = HTMLDoc.querySelectorAll("a[onclick*='UpdatePartRow']")
The two matches, for your sample, are as follows:
index 0
<a onclick="UpdatePartRow(); chkKeepSubmitPR(); return false;" href="">
index 1
<a onclick="var doc = window.document.forms[0]; UpdatePartRow(); chkKeepSubmitPR(); if (doc.OrgMatrixYes.value == "Y") { VerifyDeptOrgMatrix(); } return false;" href="">
You can access the nodeList by index e.g.
nodeList.item(0).Click
nodeList.item(0).FireEvent "onclick"

Interaction With WebPage VBA

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

VBA - getElementById works for simple website but not another?

So I'm currently stuck at getting a VBA script to retrieve the value of an input box from this Sudoku website. However, I was able to get the value from a paragraph element with the id of "contact" from my own simpler website, using the same code (after switching the url and id names, of course).
Any attempts to research further brings up articles/blogs that discuss what I've done correctly so far, so I suspect I am not researching it properly.
Here is my code:
Sub GetTable()
Dim ieApp As InternetExplorer
Dim ieDoc As Object
Dim sudokuCell As Object
Dim url, id, content As String
Dim i As Integer
Set ieApp = New InternetExplorer
ieApp.Visible = True
url = "http://www.websudoku.com/"
ieApp.navigate url
Do While ieApp.Busy: DoEvents: Loop
Do Until ieApp.READYSTATE = READYSTATE_COMPLETE: DoEvents: Loop
Set ieDoc = ieApp.document
If ieDoc Is Nothing Then
MsgBox ("Nothing")
'Else
' MsgBox ("Something")
End If
For i = 0 To 8
Set sudokuCell = ieDoc.getElementById("f00")
content = sudokuCell.innerText
MsgBox (content)
Next i
ieApp.Quit
Set ieApp = Nothing
End Sub
And here is an example of the html for a cell which is blank:
<td class="g0" id="c00"><input class="d0" size="2" autocomplete="off"
name="8iz6n11" maxlength="1" onblur="j8(this)" id="f00"></td>
And here is one for cell that is prefilled with a number:
<td class="f0" id="c10"><input class="s0" size="2" autocomplete="off"
name="s8iz6n21" readonly="" value="7" id="f10"></td>
I have tried both the "c00" an "f00" without success. Also, while I believe the problem at hand is I am not retrieving the element, I am concerned that the .innerText property won't retrieve the values.
First: The website is using FRAME, so you are not accessing the frame document in the VBA code actually. You need to navigate to the actual URL given below - change your url variable as the following (which is the frame's src property):
url = "http://view.websudoku.com/?"
Second: Those are INPUT elements you are trying to get values, you should be better using Value property instead innerText
content = sudokuCell.Value
Third and last: I have no idea what your code is supposed to do inside the loop as it will keep reading f00 element value as is. However I believe you'll loop through the input elements and just hit the wall here about the FRAME issue I explained above, so I assume loop is your part and have no trouble about it.

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>