I am just starting out with VBA and am trying to write a script that does the following interactions with a website:
Login on website
In subsequent webpage, fill in first name and last name from an excel spreadsheet and click "Submit"
In the subsequent webpage, copy an id number that is generated
I have managed to get my code to login on the website through getElementsById since the website's elements do not have any Name. However, excel throws back a Type Mismatch error for my subsequent codes to interact with subsequent webpages.
Here are the HTML script for the firstname, lastname, submit fields in the subsequent webpage:
First Name field:
<input class="tfield-def-edit form-control" id="tfield-def-edit_12803" type="text">
Last Name field:
<input class="tfield-def-edit form-control" id="tfield-def-edit_12804" type="text">
Submit button:
<button class="btn btn-block btn-success" id="btn-submit-registration" type="button">Submit</button>
Here are my VBA codes:
Sub getid()
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
URL = "https://example.website"
IE.Navigate2 URL 'load webpage
Do While IE.readyState <> 4 Or _
IE.Busy = True
DoEvents
Loop
'login using password
Set login = IE.document.getElementById("passkey")
login.Value = "123456"
Set loginbutton = IE.document.getElementById("login")
loginbutton.Click
-------------------------------CODE ABOVE WORKS-----------------------------
------------------------------ERRORS OCCUR BELOW----------------------------
While IE.Busy
DoEvents
Wend
Dim i As Integer
Dim LastRow as Long
With Worksheets("Sheet1")
Set LastRow = .Range("A" & .Rows.Count).End(xlUp).Rows
For i = 1 To LastRow
Set firstname_field = IE.document.getElementById("tfield-def-edit_12803") 'error most probably occur here
Set lastname_field = IE.document.getElementById("tfield-def-edit_12804")
Set submitbutton = IE.document.getElementById("btn-submit-registration")
firstname_field.Value = .Range("B" & i).Value
lastname_field.Value = .Range("C" & i).Value
submitbutton.Click
While IE.Busy
DoEvents
Wend
Set newregistrationbutton = IE.document.getElementByClassName("btn btn-default")
Set codeid = IE.document.getElementsByClassName("col-xs-6 col-xs-offset-3")
.Range(D & i).Value = codeid(0).textContent
newregistrationbutton.Click
Next i
End With
End Sub
My best guess is that the first name and last name fields are text elements and cannot be Set with a value. When I tried removing Set for all text elements, VBA throws me an error "Object Required".
I am also trying to copy an id that is generated in the subsequent page once the first and last name page runs successfully. I am unable to test the last 4 lines of this code since the preceding codes are not working.
I've been spending days on this and will really appreciate if all of you may shed some light on this.