Trying to get html Dropbox (2 step) working with vba code - html

Trying to get a dropbox working from vba code but it seems to have a two-step process before the drop box opens. (Like authentication, the displays a box about the dropbox so you can select and it inserts it into the box. But it is all in the one dropbox, but I think the authentication side is hidden. I can get a basic Dropbox to work with indexes but this one has me stumped. I do not fully understand as fairly new to VBA > HTML side of things.
But my understanding is "SchProgramID" is the authentication or filter code then once it has received that the "TrainerId" will open to give you selected names of which is filtered into a box as you type or you can be selected with a mouse from the list.
I cannot even get focus on either.
Can someone please help me?
The html code from the site is as follows:
<div class="form-group">
<label class="control-label col-md-2" for="TrainerId">Trainor</label>
<div class="col-md-8">
<select class="form-control chosen-select" data-live-search="true" data-val="true" data-val-number="The field Trainor must be a number." data-val-required="The Trainor field is required." id="TrainerId" name="TrainerId"><option value="">Select Trainor</option>
<option value="176">Undrico Divina Corpuz Jr.</option>
<option value="204">Domingo Bagadiong Go Jr.</option>
<option value="1200">Marnilo Sayson Sugano </option>
<option value="1238">Dexter Gaoiran Tomas </option>
Code I have been playing with
'Dim fromSelect, fromSelect1 As HTMLSelectElement
'Dim evt, evt1 As Object
'Set evt = htmlDoc.createEvent("HTMLEvents")
'Set evt1 = htmlDoc.createEvent("HTMLEvents")
'evt.initEvent "change", True, False
'evt1.initEvent "change", True, False
'Set fromSelect = htmlDoc.getElementById("SchProgramId")
'OptionValue = "14526"
'If optionIndex >= 0 Then
' fromSelect.selectedIndex = OptionValue
' fromSelect.dispatchEvent evt
'Set fromSelect1 = htmlDoc.getElementById("TrainerId")
'OptionValue = "9570"
If optionIndex >= 0 Then
' fromSelect.selectedIndex = OptionValue
' fromSelect.dispatchEvent evt1
end if

I am not clear on the role of SchProgramId at present.
For showing the dropdown you should be able to use:
ie.document.getElementById("TrainerId").Click
For selecting elements in the dropdown you should be able to target the value attribute by its value e.g. 1421 for the first trainer (or by index)
ie.document.querySelector("#TrainerId option[value='1421']").Selected = True
Example using index:
ie.document.querySelector("#TrainerId").selectedIndex = 2

Related

Value not getting updated in IE when trying to change it using VBA

I am trying to change the drop down value of a field in IE using VBA but the value is not getting updated in IE.
Below is my code:
IE.Document.getelementbyid("ddlSchemeCategory").Value = "MANAGE CASH"
Set objButton = IE.Document.getelementbyid("ddlSchemeCategory")
objButton.Focus
objButton.Click
HTML Code for the field I am trying to change:
<div class="selectbg">
<div class="selectedvalue" id="divscat">All Categories</div>
<select name="ddlSchemeCategory" tabindex="4" class="ddlSchemeCategory" id="ddlSchemeCategory" style="display: inline-block;">
<option value="-1">All Categories</option>
<option value="CREATE WEALTH">CREATE WEALTH</option>
<option value="MANAGE CASH">MANAGE CASH</option>
<option value="NFO">NFO</option>
<option value="STABLE INCOME">STABLE INCOME</option>
<option value="RETIREMENT">RETIREMENT</option>
<option value="SAVE TAX">SAVE TAX</option>
</select>
</div>
I have also tried using SelectIndex but that also did not workout for me.
You can also try these options below:
Sub firstOption()
Dim slct As HTMLSelectElement
Set slct = ie.document.getElementById("ddlSchemeCategory")
Dim opt
For Each opt In slct.getElementsBytagname("option")
If opt.Value = "CREATE WEALTH" Then 'CREATE WEALTH sample value to be selected
opt.Selected = True
slct.fireevent "onchange"
Exit For
End If
Next opt
End Sub
Sub secondOption()
Dim slct As HTMLSelectElement
Set slct = ie.document.getElementById("ddlSchemeCategory")
Dim opt
Dim evt
Set evt = ie.document.createEvent("HTMLEvents")
evt.initEvent "change", True, False
For Each opt In slct.getElementsBytagname("option")
If opt.Value = "CREATE WEALTH" Then
opt.Selected = True
slct.dispatchEvent evt
Exit For
End If
Next opt
End Sub
you can try make the change with attribute = value selector for the options and then FireEvent. You might also consider attaching a change event to the select element.
ie.document.querySelector("[value='CREATE WEALTH']").Selected = True
ie.document.querySelector("#ddlSchemeCategory").FireEvent "onchange"

How to call html form fields in vbscript dynamically in a loop

So I have an html form created in classic asp that has about 25 check boxes with different labels. The checkboxes are written to the page via a loop that grabs the label values from a table and each checkbox is named similarly ("decreason1","decreason2","decreason3",ect...) using a loop variable.
I use a vbscript at the end of the page to validate the data on the page before passing with a submit button. I need to make sure that at least one of the checkboxes is checked before submitting the form.
dim i, checkedvalue ;
checkedvalue = false
for i = 1 to 25
if document.rtftadd.decreason1.checked = true then
checkedvalue = true
end if
next
I need the "document.rtftadd.decreason1.checked" to change with the loop to decreason2, decreason3
I'm not sure how to go about doing that.
Any help would be greatly appreciated.
There are a few different ways to do this and if you are seeking a validation method prior to form submission then JavaScript may be a better solution.
However, in an effort to address your question using only ASP Server side code for VBScript and considering your question suggest that you do not care which box is selected nor how many are selected then the following code may be a working solution for you.
By looking at all of the elements sent via the form and checking if your form name (without number) exist then this same block of code will work even if you increase or decrease the number of check boxes you are validating for input.
<%#LANGUAGE="VBSCRIPT"%>
<%
dim checkedvalue
checkedvalue = false
if request("btn1") = "Submit" then
For each item in request.form
if instr(item,"decreason") > 0 then
checkedvalue = true
end if
next
response.write "Checked Value = " & checkedvalue & "<br><br>"
end if
%>
<html>
<head></head>
<body>
<form method="post" action="index.asp" name="rtftadd">
<input type="checkbox" name="decreason1"> Box 1<br>
<input type="checkbox" name="decreason2"> Box 2<br>
<input type="checkbox" name="decreason3"> Box 3<br>
<input type="checkbox" name="decreason4"> Box 4<br>
<input type="checkbox" name="decreason5"> Box 5<br>
<br>
<input type="submit" value="Submit" name="btn1">
</form>
</body>
</html>

VBA simple parse

I am using vba ( & internetexplorer object) to convert CSUIP to ISIN (these are financial security unique identification codes) from the following website http://www.isincodes.net/convert-cusip-to-isin.php.
I have so far created a vba code (in following order) that:
1. manipulates the US/CA dropdown box
2. inputs my CUSIP into the inputbox
3. clicks the "Covert"Button
Sub cusip_is2()
'declare variables
Set objie = CreateObject("internetExplorer.Application")
objie.Visible = True
'go to website
objie.navigate ("http://www.isincodes.net/convert-cusip-to-isin.php")
Do
DoEvents
Loop Until objie.readyState = 4
'input the CA in the country ID step1
objie.document.getelementbyID("country").Value = "CA"
'input 912796HQ5 in text box as desired CUSIP to convert
objie.document.getelementbyID("appendedInputButton").Value = "912796HQ5"
'press the button to convert
Set ElementCol = objie.document.getElementsByTagName("button")
For Each btnInput In ElementCol
btnInput.Click
Next btnInput
'wait until the pages loads (not sure if I need this)
Do
DoEvents
Loop Until objie.readyState = 4
'added extra few seconds incase HMTL document is updating
Application.Wait Now + TimeSerial(0, 0, 1)
'created userform to look at the data to see if I can find the converted CUSIP - WHICH I CANNOT (HELPPPPP!!!!)
Userfrom_Web_Code.Textbox_Webform.Text = objie.body.innerText
Userfrom_Web_Code.Show
'clean up and try again for the next failure LOL
objie.Quit
Set objie = Nothing
End Sub
From my research I know that I keep getting the source code but I want the DOM, this is where I am having trouble. Please see EXTRACT of source code on the website once I have inputted "CA" for country and the CUSIP "912796HQ5", and note that the id tag with results contains nothing.
<p>Enter a CUSIP and a correct ISIN will be calculated for you, if possible:</p>
<form class="form-inline">
<div class="input-append">
<select id="country" style="width:60px;">
<option value="CA">CA</option>
<option value="US" selected>US</option>
</select>
<input type="text" maxlength="9" class="span3" id="appendedInputButton">
<button type="button" class="btn">Convert</button>
</div>
</form>
<div id="results"></div>
<br><br>
</div>
<div class="span4">
<h4>What is a CUSIP?</h4>
<p>A CUSIP is a 9-character alphanumeric code which identifies a North American financial security.</p>
<p>
A CUSIP consists of three parts:<br>
• A six-character issuer code<br>
• A two-character issue number<br>
• A single check digit.<br><br>
For example: 780259206 (Royal Dutch Shell-A)
</p>
conversely when I check the inspect element which takes me to the "DOM" then I can see this under id results.
<div id="results" style="display: block;"><br>
<b>Strict Standards</b>: Non-static method Validate_CUSIP::validate() should not be called statically in <b>/home/isincode/public_html/action/c.php</b> on line <b>15</b><br>
<p class="text-success"><strong>Correct ISIN: CA912796HQ58</strong></p></div>
Can anyone please help me solve this problem in vba.
Note that I know that you can create an algorithm yourself in vba/excel to do the conversion of CUSIP to ISIN however I want to do this project in VBA to learn parsing. I am also very new to coding and have had limited exposure to please be kind and explain everything you suggest.
Please see if the following edit will suit you:
....
....
'added extra few seconds incase HMTL document is updated
Application.Wait Now + TimeSerial(0, 0, 2)
Dim ISIN As String
ISIN = Right(objie.document.getelementbyID("results").innerText,12) 'the 12 rightmost characters
Debug.Print "ISIN you are looking for is: " & ISIN
....
Edit the code to do something usefull with the ISIN-string

How to run website forms in Excel without having to use Sendkeys?

I am trying fill out a form on a website using Excel VBA. I have created an InternetExplorer.Application, navigated to the page and looked up a bunch of data, using If UserForm1.TC2.Value = True Then or something like PostCode = objIE.document.getElementsByName("ProjectFile-ProposalAddress-PostCode")(0).Value and the like.
Afterwards, I navigate to a new page, and look to fill it out using my previous data.
And this is where I run into trouble. I want to tick a check box 'New Permit', and its code is;
<form id="document-form">
<div class="generate-form form-horizontal">
<div class="form-group"><label class="col-sm-3 control-label"><span>New Permit</span></label><div class="input col-sm-7">
<div class="checkbox">
<input type="checkbox" data-bind="checked: NewPermit" />
</div></div></div><div class="form-group"><label class="col-sm-3 control-label"><span>Staged Permit</span></label><div class="input col-sm-7">
<div class="checkbox">
<input type="checkbox" data-bind="checked: StagedPermit" />
</div>
Which has no name to lock into. I'm not a HTML expert, but there is some more code that refers to this tickbox (I think)
var model = { "NewPermit": null, "StagedPermit": null, "AmendedPermit": null,
etc.
I have run a loop through the code using .getElementsByTagName("Span") with various .tagName etc. The following results is for the New Permit box:
.tagName = Span
.outerHTML = New Permit
.outerText = .innerHTML = .innertext = New Permit
.isContentEditable = False
.tostring = [object HTMLSpanElement]
.ID = ""
This is behind a password log in, and I cannot post the link publicly. But can work through PM etc to get to the answer.
Use getElementsByTagName('input') and then use Checked = True
Dim element as Object
element = getElementsByTagName('input')
element.Checked = True
assumes checkbox is the only input element on the page. If not, make a loop and identify the desired checkbox

HTML.DropDownList not showing the selected value

Please a really need some help. I getting crazy with this one.
I'm trying to build in a page 7 Tab's with 2 DropDown's in for selecting value. The list his always the same but in each tab i have a different selected value.
Everything goes well with the first one but i can't make the second one work.
Her is my Razor code:
#Html.DropDownList("Q21_objectivos", new SelectList
(Model.Q21_ObjectivosList, "Value", "Text", Model.Q21_Objs[i - 1]),
"Seleccione um objectivo",
new
{
id = "objectivo" + i.ToString(),
#class = "form-control",
#onchange = "detectarObjectivoDuplicado( " + i + ", $(this).val() );"
})
This one is not working:
#Html.DropDownList("Q21_AvaliacaoLista",
new SelectList(Model.Q21_AvaliacaoLista, "Value", "Text", Model.Q21_Pontuacao[i - 1]),
new
{
id = "avalObjectivo" + i.ToString(),
#class = "form-control",
#onchange = "CalculaPontRes();"
})
Here is the resulting HTML:
<select class="form-control" id="objectivo1" name="Q21_objectivos" onchange="detectarObjectivoDuplicado( 1, $(this).val() );"><option value="">Seleccione um objectivo</option>
<option selected="selected" value="1">Preencher as tarefas em DotProject até ao dia 1 do mês seguinte</option>
<option value="2">Desenvolver aplicação SIADAP3</option>
<option value="3">Resolver 70% dos tickets atribuidos</option>
<option value="4">Desenvolver 2 aplicações locais em VB.net</option>
<option value="5">Desenvolver 2 aplicações locais em COBOL</option>
</select>
The resulting HTML of the not selecting dropdownlist:
<select class="form-control" id="avalObjectivo1" name="Q21_AvaliacaoLista" onchange="CalculaPontRes();"><option value="5">Superado (Pontuação 5)</option>
<option value="3">Atingido (Pontuação 3)</option>
<option value="1">Não Atingido (Pontuação 1)</option>
<option value="0">Avalie o Objectivo</option>
</select>
What can I say more... The model is loaded with the list as it's possible to see in the resulting HTML.
If you change the property name "Q21_AvaliacaoLista" to something else, the selectedvalue will work.
The property name (Q21_AvaliacaoLista) and the list of items (Model.Q21_AvaliacaoLista) cannot have the same name.
Maybe it is because of data biding of MVC...
I just made it work by changing "Q21_AvaliacaoLista" to "Q21_Avaliacao" in the DropDownList that wasn't working.
Somehow the name was making probably a conflict. I don't understand why but this way it's working.