VBA: Access element inside a div loaded with angularjs, when ID and Classname changes randomly - html

I am a beginner in VBA and I make an application that fills the data coming from a xls page to a website that uses angularjs.
the website contains a table to fill out, so its ID and classname changes the four latest number randomly with each refresh. (for exemple: the code source below: 02XC of ID will be change to something different, but the prefix will remain the same). how can i manipulate this table?
Code source web site
<div tabindex="-1" class="ui-grid-cell ng-scope ui-grid-coluiGrid-02XC cell editable" id="1554799061475-1-uiGrid-02XC-cell" role="gridcell" aria-selected="false" ng-class="{ 'ui-grid-row-header-cell': col.isRowHeader }" ng-repeat="(colRenderIndex, col) in colContainer.renderedColumns track by col.uid" ui-grid-cell="" ui-grid-one-bind-id-grid="rowRenderIndex + '-' + col.uid + '-cell'">[Here is the web table that i want to upload values][1]</div>
my code
Set objHtml = New HTMLDocument
Set objHtml = internetExplorer.document
Set modric = objHtml.getElementsByClassName("ui-grid-cell ng-scope ui-grid-coluiGrid-02XC cell editable")
If modric.Length <> 0 Then
For q = 0 To modric.Length - 1
modric(q).Click
modric(q).innerText = Workbooks("remplir").Worksheets("sheet1").Range("F1").Offset(n + 1, 0).Value
Next q
End If
as i said, in the next refresh, 02XC 'll be change to a four other random number.
I want to get the ID or classname for each refresh to manipulate the table.
or every others ways that could help me to manage the table.
sorry my English is so poor. hope your understand me :)

You can use attribute = value selector with starts with (^) operator
[id^='1554799061475-1-uiGrid-']
I am not sure if you want a single or multiple matches
single match
Dim ele As Object
Set ele = objHtml.querySelector("[id^='1554799061475-1-uiGrid-']")
This assumes the id starts with 1554799061475-1-uiGrid- and only the end bit changes.
You can use querySelectorAll to return a nodeList if more than one match possible.

Related

Identify NextSibling in XMLHTTP response

I am still trying to learn about NextSibling and I am using XMLHTTP in excel VBA.
Here's the HTML for the element
<ul class="list-unstyled list-specification">
<li><span>ID</span> <span class="text-info">22928</span></li>
<li><span>Category</span> <span class="text-info">Mechanical</span></li>
<li><span>Discipline</span> <span class="text-info">Mechanical </span></li>
<li><span>Commodity</span> <span class="text-info">Pipe</span></li>
<li><span>Sub commodity</span> <span class="text-info">12 In Pipe </span></li>
<li><span>UOM</span> <span class="text-info">EA</span></li>
<li><span>Available quantity</span> <span class="text-info">30</span></li>
<li><span>Age</span> <span class="text-info">8</span></li>
</ul>
I have used this line to spot on the first span in the li (lists) so as to identify the headers for each part
Set post = html.querySelectorAll(".list-specification li span")
Then I used loops like that
For j = 0 To post.Length - 1
If post.Item(j).innerText = "ID" Then
Debug.Print post.Item(j).NextSibling.innerText
End If
Next j
I got an error when trying to use NextSibling. I feel stuck as for that NextSibling .. Can you guide me?
for example ID is the first in the list and I would like to get that ID based on my approach
I got an error when trying nextElementSibling
Sub Test()
Dim html As New HTMLDocument, post As Object, i As Long
With CreateObject("MSXML2.XMLHTTP")
.Open "Get", "C:\Sample.html", False
.send
html.body.innerHTML = .responseText
End With
Set post = html.querySelectorAll(".list-specification li span")
For i = 0 To post.Length - 1
If post.Item(i).innerText = "ID" Then
MsgBox post.Item(i).nextElementSibling.innerText: Exit For
End If
Next i
End Sub
Try doing another NextSibling and then you should find it working:
Set post = Html.querySelectorAll(".list-specification li span")
For j = 0 To post.Length - 1
If post.Item(j).innerText = "ID" Then
MsgBox post.Item(j).NextSibling.NextSibling.innerText
Exit For
End If
Next j
The correct property to access I was expecting to be nextElementSibling, but it seems VBA does not implement this.
The NonDocumentTypeChildNode.nextElementSibling read-only property
returns the element immediately following the specified one in its
parent's children list, or null if the specified element is the last
one in the list.
You can however, more correctly, simply take the next index in post i.e. post.item(1). You are collecting both headers and values in the same nodeList so you can use odd/even distinction to separate headers from values.
You can see this if you run the following in console:
post = document.querySelectorAll(".list-specification li span");
var res = ''; for (let [i] of Object.entries(post)) {res += post.item(`${i}`).innerText + ' '};console.log(res);
Spans are inline containers and you can see from html that you have a space between spans which is part of the parent li and this becomes a child text node. This is why your nextSibling hits a text node and errors with the attempt at .innerText accessor. You would want a text node property such as .nodeValue (if you were at the right node).
You can step through, in the console, and see the different properties in action:
As nextElementSibling is not implemented in VBA you would need to chain nextSibling, as per #Sim's answer, if you want to explore nextSibling to solve this particular navigation. However, note that a test of nodeType would avoid throwing an error as you could then apply the appropriate accessor.

Can I store the same option value for more than one toggle button in a control box?

I have a list of questions each with 4 possible answers that are displayed as toggle buttons on my form. What I want to do is if the user chooses either of the first two buttons, the Option Value stored is "1", if they choose either of the last two buttons, the Option Value stored should be "0". The option values must be different for each toggle button in a control group. Is there a way to recode the toggle buttons to store the desired response? (I work in psychology, thus the bait and switch of offering 4 choices to the user when really only two responses are recorded).
Here is what I have tried:
I tried thinking about a recode as jcarroll suggested, but this is a circular reference:
Private Sub Q1_Click()
If Me.Q1 = 1 Or 2 Then
Me.Q1 = 1
Else:
Me.Q1 = 0
End If
End Sub
I could recode into another variable but that is just as clunky as using a SQL statement on the data post-hoc, for instance:
NewVariable=Iif([Q1]=1,1,iif([Q1]=2,1,0)
Finally, I tried to code have both toggle buttons have the same Option Value (which causes both to look pressed if either is pressed) and recode the unpressed toggle button's back color. But while my code looks correct to me, this did not change the pressed color of the toggle button (which I think has to do with over riding toggle button design settings):
Private Sub Frame5_Click()
If Toggle8.Value = True Then
Toggle9.BackColor = &HFF00&
Else
Toggle9.BackColor = &H8000000F
End If
End Sub
I could not come up with any programming solutions on the form itself to solve this. The alternative is that I wrote a procedure to apply to the data after it is collected which will be stored as 1,2,3,4 to convert it to 0 or 1. This procedure also sums up the 1's. I have 50 variables/questions that will be passed through this procedure (as well as another like it that converts 3&4 to 1).
Public Function Recode1(ParamArray arg()) As Variant
Dim Size As Integer, skips As Integer, i As Integer, result As Variant
'Recodes first two toggle buttons as "1" for AQ assessment
Size = UBound(arg) + 1
For i = 0 To Size - 1
If IsNull(arg(i)) Or Not (IsNumeric(arg(i))) Or arg(i) = -99 Then
skips = skips + 1
Else
If arg(i) = 1 Or arg(i) = 2 Then
result = result + 1
Else:
result = result + 0
End If
End If
End sub

Compare index of 2 elements in a collection

Issue : I have some issues figuring out a way to select elements in my HTMLDocument which are under a certain point in the page.
In the following code sample, as you can see in the comments, I first select a part of them which respect my queryselector criteria
IEDoc.querySelectorAll("td[width='100'][class='ListMainCent'][rowSpan='1'][colSpan='1']")
In this example I have 10 elements in this collection. Each of this element in contained in a table which is its parent on the 7th degree.
MsgBox TypeName(IEDoc.querySelectorAll("td[width='100'][class='ListMainCent'][rowSpan='1'][colSpan='1']")(2).ParentNode.ParentNode.ParentNode.ParentNode.ParentNode.ParentNode.ParentNode) ' HTMLTable
Some of those elements are in the same table.
You can see here the form which contains all the tables .
Now, the thing is that I want to select the innerHTML of some of those elements only and not all of them. The criterion to know if I one of those 10 elements interests me or not is it's position on the webpage. I want all the elements which are under the message Part Usage. There is only one table containing the Part Usage text and so my idea was to see if the table in which are contained each element has a higher or lower index in the "form" collection.
If the index is higher I want this element, otherwise I discard it.
What I did for this is the following code :
I set the ID Bim to all the tables containing one or more
from the 10 elements.
For Each Element In IEDoc.querySelectorAll("td[width='100'][class='ListMainCent'][rowSpan='1'][colSpan='1']") ' here for all of the 10 numbers found with the queryselectorall we'll find their respective table in the collection (form) and set its Class as "Bim". But since some of the numbers are in the same table, we won't have 10 tables with a classname "Bim" at the end of the process. We'll have only x tables with the classname "Bim"
Element.ParentNode.ParentNode.ParentNode.ParentNode.ParentNode.ParentNode.ParentNode.Class = "Bim"
Next
I set the ID Stop to the table containing the text Part Usage
For Each Element In IEDoc.getElementsByClassName("SectionHead")
If Element.innerHTML = "Part Usage" Then
'MsgBox TypeName(Element.ParentNode.ParentNode.ParentNode)' HTMLTable
Element.ParentNode.ParentNode.ParentNode.ID = "Stop"
End If
Next
I check which tables with the Classname Bim are under (=higher index) the table with the ID Stop. For the table ( there is actually only one) matching the criterion of point 3 I apply IEDoc.querySelectorAll("td[width='100'][class='ListMainCent'][rowSpan='1'][colSpan='1']") inside of them so that I get all the elements in contains and more paricularly their innerHTML.
For Each Element In IEDoc.getElementsByClassName("Bim") ' Here we check all the x tables which have the Classname "Bim"
If Element.indexInTheWholeForm > IEDoc.getElementById("Stop").indexInTheWholeForm Then 'and compare somehow if their index in the (form) collection if higher than the table with the ID "Stop" ( this is similar to checking if the element if lower on the webpage in thic case) ( we only want the element which have a higher index aka under the Part Usage table)
For Each Element2 In Element.querySelectorAll("td[width='100'][class='ListMainCent'][rowSpan='1'][colSpan='1']") ' Now we are in the table which contains the part numbers and we'll look for all the part numbers it contains by applying the queryselectorall again, but this time only in this specific table
array_parts2(iteration2) = Element.querySelectorAll("td[width='100'][class='ListMainCent'][rowSpan='1'][colSpan='1']")(iteration2).innerHTML
ActiveWorkbook.Worksheets(1).Cells(iteration2 + 1, 19) = array_parts2(iteration2)
iteration2 = iteration2 + 1
Next
End If
Next
of course what doesn't work is the indexInTheWholeForm property which doesn't exist. Any ideas on how to do this ?
Thank for reaching that line :)
Untested but I would do something like this (assuming I understood you correctly)
Sub Tester()
Const S_MATCH As String = "td[width='100'][class='ListMainCent'][rowSpan='1'][colSpan='1']"
Dim e, tbl, bHit As Boolean
'...
'load page etc
'...
'get all the matching rows and cycle though them
For Each e In IEDoc.querySelectorAll(S_MATCH)
'did we get to the table of interest yet?
If Not bHit Then
Set tbl = e.ParentNode.ParentNode.ParentNode.ParentNode. _
ParentNode.ParentNode.ParentNode
If IsPartUsageTable(tbl) Then bHit = True
End If
If bHit Then
'we reached the table of interest, so
' do something with e
End If
Next
End Sub
Function IsPartUsageTable(tbl) As Boolean
Dim e, rv As Boolean
For Each e In tbl.getElementsByClassName("SectionHead")
If Element.innerHTML = "Part Usage" Then
rv = True
Exit For
End If
Next
IsPartUsageTable = rv
End Function
Ok, so as unexpected as it sounds, I think I found a solution to my own question. I will confirm you that it works as soon as I have the possibility to run it with my colleague.
So I keep point 1 and 2 from my initial post and I replaced point 3 with the following :
For i = 0 To IEDoc.getElementsByTagName("form")(0).getElementsByTagName("table").length
If IEDoc.getElementsByTagName("form")(0).getElementsByTagName("table")(i).ID = "Stop" Then
index_Part_Usage = i
Position_Part_Usage = index + 1
Exit For
End If
Next
'MsgBox Position_Part_Usage
For i = 0 To IEDoc.getElementsByTagName("form")(0).getElementsByTagName("table").length
If IEDoc.getElementsByTagName("form")(0).getElementsByTagName("table")(i).className = "Bim" Then
index = i
Position = index + 1
If index > index_Part_Usage Then
For Each Element2 In IEDoc.getElementsByTagName("form")(0).getElementsByTagName("table")(i).querySelectorAll("td[width='100'][class='ListMainCent'][rowSpan='1'][colSpan='1']") ' Now we are in the table which contains the part numbers and we'll look for all the part numbers it contains by applying the queryselectorall again, but this time only in this specific table
array_parts2(iteration2) = IEDoc.getElementsByTagName("form")(0).getElementsByTagName("table")(i).querySelectorAll("td[width='100'][class='ListMainCent'][rowSpan='1'][colSpan='1']")(iteration2).innerHTML
ActiveWorkbook.Worksheets(1).Cells(iteration2 + 1, 19) = array_parts2(iteration2)
iteration2 = iteration2 + 1
Next
End If
End If
Next i

Referencing unchecked checkboxes with vbscript causes an error

I am running into a problem with my vbscript code. My HTML code looks like this
<input type='checkbox' name='DisplayRow' id='DisplayRow1' />
<input type='checkbox' name='DisplayRow' id='DisplayRow2' />
<input type='checkbox' name='DisplayRow' id='DisplayRow3' />
This is done because above there is another checkbox that calls a javascript function that will check or uncheck all of the "DisplayRow" checkboxes. The javascript function uses getElementsByName to return all of the checkboxes named "DisplayRow".
When the form's submit button is clicked the action sends it to an ASP page (classic ASP) that grabs all of the objects on the calling form by using the Request.Form command. The Request.Form command looks at the "name" attribute, not the "id" attribute of the object.
This seems to be working fine for all of the other form objects. When it gets to the checkboxes because the "name" attribute uses the same name for all of the check boxes it returns an array. The individual checkboxes can be accessed like this:
Request.Form("DisplayRow")(x)
Where x references the individual checkbox in the array.
If the checkboxes are checked I can loop through the array without any problems. If 1 or more or all of the checkboxes are unchecked then when the code references the first checkbox in the array that is unchecked the page crashes. Nothing is executed after the Request.Form command fails.
I have tried enclosing the Request.Form("DisplayRow")(x) in an IsNull function in an If statement but it still takes the program down.
Has anyone else ran into this and found a work around?
Edit
For some reason stackoverflow is not letting me add more than one comment.
#Cory. Thanks for the information
#jwatts1980. Count works but it does not let me know which of the checkboxes are checked. If the count is greater than 0 I can loop through them but if the first one is unchecked I am right back where I started with a crashed page.
You cannot do it this way because unchecked checkboxes will not be submitted in the post, only the checked ones.
I would approach this differently:
First I would add a value attribute to the checkboxes, as so:
<input type='checkbox' name='DisplayRow' id='DisplayRow1' value="1" />
<input type='checkbox' name='DisplayRow' id='DisplayRow2' value="2" />
<input type='checkbox' name='DisplayRow' id='DisplayRow3' value="3" />
Notice the value is the same as the index, this will be needed in the code.
Next I would use .Split() to gather the checkboxes selected in an array, since the values will come in as a string separated by comma, ie: 1,2,3 to your .Form() value.
Rows = Request.Form("DisplayRow")
'check if any are selected first
If Rows <> "" Then
'make an array with each value selected
aRows = Split(Rows,",")
'loop through your array and do what you want
For i = lBound(aRows) to uBound(aRows)
Response.Write "DisplayRow" & aRows(i) & " was Selected."
Next
End If
This way you only process the results for the one's selected, and ignore the others.
I've always found this essential for my library...
'GetPostData
' Obtains the specified data item from the previous form get or post.
'Usage:
' thisData = GetPostData("itemName", "Alternative Value")
'Parameters:
' dataItem (string) - The data item name that is required.
' nullValue (variant) - What should be returned if there is no value.
'Description:
' This function will obtain the form data irrespective of type (i.e. whether it's a post or a get).
'Revision info:
' v0.1.2 - Inherent bug caused empty values not to be recognised.
' v0.1.1 - Converted the dataItem to a string just in case.
function GetPostData(dataItem, nullVal)
dim rV
'Check the form object to see if it contains any data...
if request.Form = "" then
if request.QueryString = "" then
rV = nullVal
else
if request.QueryString(CStr(dataItem))="" then
rV = CStr(nullVal)
else
rV = request.QueryString(CStr(dataItem))
end if
end if
else
if request.Form(CStr(dataItem)) = "" then
rV = CStr(nullVal)
else
rV = request.Form(CStr(dataItem))
end if
end if
'Return the value...
GetPostData = rV
end function
To use the function you simply pass in the form or query string item you're looking for and what to replace empty values with...
Dim x
x = GetPostData("chkFirstOne", false)
You can keep using your existing code by adding a single condition:
If Request.Form("DisplayRow").Count > 0 Then
'your code here
Else
'consider adding message saying nothing was selected
End If

VBS: Can I target a field by its tabIndex, and its div position?

Novice here, using VBS to help with data entry to a web input form. Would appreciate any advice. I regularly use lines like this to set the value of a field based on its name:
IE.Document.All.Item("field1").Value = "test"
However I have a set of very awkward fields whose names change with each record. Their physical positions stay the same (visually); their tabIndexes stay the same (1,2,3,4), so I wondered if it's possible to do something like this:
IE.Document.All.getElementByTabIndex(1).Value = "test"
...But I'm not sure it is? Furthermore, even if that did work, tabIndex1 is used for another field on the same webpage. The fields that I am interested in, however, are all located on a div. The ID of the div is "form_div". So I'm trying to target a field located on div "form_div" whose tabIndex is 1... do you think it is possible?
Big thanks in advance.
So you have a DIV element with tabIndex set to 1 and you don't know it Name or ID, right? Then do something like this:
Set oDivs = IE.Document.getElementsByTagName("div")
Set myDiv = Nothing
For Each od In oDivs
If od.tabIndex = "1" Then
Set myDiv = od
Exit For
End If
Next
If Not myDiv Is Nothing Then
'do what needs here...
MsgBox myDiv.Name
End If
P.S. Well, I see 2 drawbacks in your design.
The tabIndex should be unique.
Searching for element by name is not so perfect in IE. If your
element has only Name and not ID then getElementsByName will
fail. Better use ID, it's even simplify coding:
Set myDiv = IE.Document.All.form_div
To find it by Name w'd be:
Set oDivs = IE.Document.getElementsByTagName("div")
Set myDiv = Nothing
For Each od In oDivs
If od.Name = "form_div" Then
Set myDiv = od
Exit For
End If
Next
And once you have the element...
If Not myDiv Is Nothing Then
Set nodes = myDiv.childNodes
For i = 0 To nodes.Length-1 Step 2
If nodes(i).tabIndex = "1" Then
'do what need here...
nodes(i).Value = nodes(i).tabIndex
Exit For
End If
Next
End If