PDA

View Full Version : Assistance With Simplifying getElementsByName Coding



bklocinski
02-22-2015, 11:38 AM
The code below is used to fill a form in an IE window. The code works but I would think there should be a way to simplify the code such as an If / ElseIf statement using getAttribute (Name) and populate the value without separate For Each statements. Any suggestions for simplification are greatly appreciated.




Set ElementCol = IE.Document.getElementsByName("state")
For Each ele In ElementCol
If ele.getAttribute("name") = "state" Then
ele.Value = "AL"
Exit For

End If
Next
'Select Due Date Month
Set ElementCol = IE.Document.getElementsByName("due_date_Month")

For Each ele In ElementCol
If ele.getAttribute("name") = "due_date_Month" Then
ele.Value = "07"
Exit For

End If
Next

'Select Due Date Day
Set ElementCol = IE.Document.getElementsByName("due_date_Day")
For Each ele In ElementCol
If ele.getAttribute("name") = "due_date_Day" Then
ele.Value = "20"
Exit For

End If
Next





Source:

The HTML below is on the second page of the form on sweepstakes.everydayfamily.com/Sweepstakes/win-a-18999-safety-1st-advance-se-65-air-convertible-car-seat3



div>

<div class="form_row2">

<label for="state">State: *</label>

<select class="required" name="state">

<option value="" selected="selected">Select a State</option>

<option value="AL">Alabama</option>

<option value="AK">Alaska</option>



div id="due_date_row" class="form_row">



<label for="due_date_Month">Due Date or Child's Birthday: *</label>

<div id="due_date">

<select name="due_date_Month" class="required">

Bob Phillips
02-23-2015, 01:30 AM
I don't think you can avoid the loops as you are looking at different elements, but you rationalise the code somewhat


'Select state
Call GetElementValue(IE, "state")

'Select Due Date Month
Call GetElementValue(IE, "due_date_Month")

'Select Due Date Day
Call GetElementValue(IE, "due_date_Day")

'............

Public Function GetEelementValue(ByVal IE As Object, Name As String) As String

Set ElementCol = IE.Document.getElementsByName(Name)
For Each ele In ElementCol

If ele.getAttribute("name") = Name Then

GetEelementValue = "AL"
Exit For
End If
Next
End Function