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

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

Related

VBA - Filling input boxes in Internet Explorer not working

I'm having the following problem which is once I populate some inputbox on IE with information from Excel using VBA, these are populated correctly but when i change onto the second line with input boxes (they all are the same in format) the one I filled before does not get saved (even if I press save).. the only way I found for the information to remain is if I get into any of these boxes I'm filling and type something manually.
Anyone has an idea of why this might be?
Thanks!
For Each cell In wsbd.range(range("A6"), range("A6").End(xlDown))
additemsbtn.Click
Set aNodeList = ieDoc.querySelectorAll("[dojoinsertionindex]")
aNodeList.Item(0).Click
For i = 0 To 15
If ieDoc.getElementById("meetingResultsPlanningTable").getElementsByTagName("select")(0).Item(i).innerText = wsbd.range("A6").Value Then
ieDoc.getElementById("meetingResultsPlanningTable").getElementsByTagName("select")(0).Item(i).Selected = True
Exit For
End If
Next i
Set dropOptions = ieDoc.getElementById("meetingResultsPlanningTable").getElementsByTagName("select")(5)
dropOptions.Value = "Value"
Set itemName = ieDoc.getElementById("dynamicLineItems").getElementsByClassName("InputBox")(0)
itemName.Value = wsbd.range("F6").Value
Set itemName = ieDoc.getElementById("dynamicLineItems").getElementsByClassName("NumInputBox2")(0)
itemName.Value = wsbd.range("J6").Value
Set itemName = ieDoc.getElementById("dynamicLineItems").getElementsByClassName("NumInputBox")(0)
itemName.Value = wsbd.range("Q6").Value
Set itemName = ieDoc.getElementById("dynamicLineItems").getElementsByClassName("NumInputBox")(1)
itemName.Value = wsbd.range("T6").Value * 100
Set itemName = ieDoc.getElementById("dynamicLineItems").getElementsByClassName("NumInputBox")(1)
itemName.Value = itemName.Value + 0
'Set savebtn = ieDoc.getElementById("/images/buttons/save.gif")
' savebtn.Click
Next cell
The code is working and is reading properly all the inofrmation in Excel, finding the corresponding Input boxes and populating them but then nothing gets saved or recorded.. as you can see I tried saving after completing the boxes but it still doesn't work...
I came up with a solution! And pretty simple by the way.. I just added a fireevent ("onchange") for each input box and that records all changes!
Set itemName = ieDoc.getElementById("dynamicLineItems").getElementsByClassName("InputBox")(0)
itemName.Focus
itemName.FireEvent ("onchange")
itemName.Value = somevalue.Value

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

Get text in a div that doesn't have a name or id

I would like to get the text inside this code:
<div class="js-text-container"></div>
when there is an ID, i use getelementbyId, no problem, but in this case no ID and even nothing inside the 2 >< (although something is displayed)
I found an interesting solution here and tried to adapt it to my case:
Dim divs = WebBrowser1.Document.Body.GetElementsByTagName("div")
For Each d As HtmlElement In divs
If d.GetAttribute("class") = "js-text-container" Then
TextBox1.Text = d.InnerText
End If
Next
But nothing appears in my textbox. Do someone have an idea? I think its because InnerText refers to nothing in this case...
I hope I was clear enough.
Thanks a lot
Instead of d.GetAttribute("class") = "js-text-container"
use
d.GetAttribute("className") = "js-text-container"
I tested it locally, I believe you can use it in VB.Net
foreach (HtmlElement el in webBrowser1.Document.GetElementsByTagName("div"))
if (el.GetAttribute("className") == "js-text-container")
{
textBox1.Text = el.InnerText;
}
Hope it helps!

VBA code that changes background color of form conditionally by answer

I want to use VBA (or some other solution) to conditionally change the background color of a form based off what number users enter in a numeric field. Basically, after they enter their answer to the Starter question, if they entered 1 then I want the form background to change to a specific shade of blue, and if they entered 2 then I want the form background to change to a specific shade of green. I saw a code that looks like it would be very similar to my need in another question on here, but I couldn't figure out how to make the code work, and was having trouble figuring out exactly how/where to put each module.
Some information:
The field I want it to be based off of is numeric, called Starter, and through data validation users are limited to entering 1, 2, 9, or leaving it blank. I only want the color to change if it's entered as 1 or 2.
I'm using Access 2010
the form has neither header nor footer
the code I was attempting to use and made some alterations to is the following:
Private Sub Form_AfterUpdate()
blue_yes = "15325906"
green_no = "13888226"
Dim colorThis As String
booWhatever = Me.Starter ''Use of the variable can prevent problems
If booWhatever = 1 Then
colorThis = "blue_yes"
End If
If booWhatever = 2 Then
colorThis = "green_no"
End If
subFrm.Form.Section(acDetail).BackColor = colorThis
subFrm.Form.Repaint
End Sub
I've also managed, off a very different piece of code, to sort of do what I want, but the way it's working it seems to change the status of all forms, not just the one I'm currently working with, which is the goal. So for example if I enter 2 to starter, it changes the background color of every single record's form.
Private Sub Starter_AfterUpdate()
If Me.Starter = "1" Then Me.Detail.BackColor = vbBlue
If Me.Starter = "2" Then Me.Detail.BackColor = vbGreen
End Sub
EDIT:
Welp, embarrassingly I found the solution. It's not a very neat one, but it works.
Private Sub Form_Current()
Dim Presence As String
Presence = Nz(Me.Starter.Value, 9)
Select Case Presence
Case "1"
Me.Detail.BackColor = 15325906
Case "2"
Me.Detail.BackColor = 13888226
Case Else
Me.Detail.BackColor = vbWhite
End Select
End Sub
Private Sub Starter_AfterUpdate()
Dim Presence As String
Presence = Nz(Me.Starter.Value, 9)
Select Case Presence
Case "1"
Me.Detail.BackColor = 15325906
Case "2"
Me.Detail.BackColor = 13888226
Case Else
Me.Detail.BackColor = vbWhite
End Select
End Sub
I know it is a really old question (probably you have already solved it in a better way) but I will give it a try anyways.
Try the following:
Private Sub Text0_Change()
Select Case Me.Text0.Text
Case ""
Case "1"
Me.Detail.BackColor = 15325906
Case "2"
Me.Detail.BackColor = 13888226
Case Else
Me.Detail.BackColor = vbWhite
End Select
End Sub
EDIT:
I tried that and it works I think now as it supposed to do.
When you change the text on the text box triggers this event every time, runs the Sub, checks it's own text and changes the color of the form as described.
The change is that I changed the property of the field it checks. From Value to Text. We want when the event triggers to check the current text because the Value property updates when you "finish" with the textbox (after you press enter or the focus on the control is lost) and we want the change to happen the same moment we press the key changing the value and not later.
The second change and the reason we got strange patterns before is that I have added one more Case when the text is "" to do nothing on that change (empty case). Without that case when we used delete or backspace to remove the text and left the textbox empty ("") then the case else was True and it changed the background color.
I hope this is the correct answer now. Please let me know!

ms access - set position of cursor in textfield to start only if textbox is empty

What I would like to do is in my formatted (inputmask) textbox set the cursor position to the first position if there is nothing in the textbox. BUT if there is something set the position to where ever the user clicked.
Right now I have:
If (txtCR.Value = "" Or IsNull(txtCR.Value)) Then
Me.txtCR.SelStart = 0
End If
But even if there is something in the textbox the cursor is moved to the first position.
Is there a way to do this?
Thanks!
Maybe this will work for you? (MsgBox line to see if you are getting the right value. You can take it out for production, obviously.)
If (txtCR.Value = "" Or IsNull(txtCR.Value)) Then
Me.txtCR.SelStart = 0
Else
Me.txtCR.SelStart = Me.txtCR.SelStart + Me.txtCR.SelLength
End If
MsgBox Me.txtCR.SelStart