Write in an HTML input field using Excel VBA

dupont picture dupont · Aug 6, 2016 · Viewed 11.8k times · Source

I load an internet page and log in with myusername and mypassword using VBA.

I would like to write a search-term in an input field of the webpage using VBA.

Because there is no name and ID in the input field, I didn't succeed.

Here is my code :

Sub MyLogin()

Dim IE As InternetExplorer
Set IE = CreateObject("InternetExplorer.Application")
With IE
    .Visible = True
    .navigate "https://www.example.com"

    Do Until .readyState = 4
        DoEvents
    Loop

    .document.all.Item("username").Value = "myusername"
    .document.all.Item("password").Value = "mypassword"
    .document.forms(0).submit

End With

Do Until IE.readyState = 4
    DoEvents
Loop

Dim inputfield As HTMLInputElement
For Each inputfield In IE.document.getElementsByTagName("input")
    If inputfield.Type = "text" Then inputfield.Value = "mysearch"
Next

Do Until IE.readyState = 4
    DoEvents
Loop

End Sub

The HTML field I want to fill:

input class="input-inboxsearch form-control" type="text" value="" placeholder="Nom, email" maxlength="71"

How can I set the value of the input field?

Answer

Robin Mackenzie picture Robin Mackenzie · Aug 7, 2016

Further to @Miqi180's comment, you can try replacing your the section of your code starting with Dim inputfield As HTMLInputElement with this:

Dim inputfield As Object
Set inputfield = IE.document.getElementsByClassName("input-inboxsearch form-control")
If inputfield.length > 0 Then
    inputfield(0).Value = "mysearch"
End If

'carry on with your code

The getElementsByClassName method will return a collection so you have to check its length and then access the items of the collection. If there is only one element with that class then you can reference the 0th element of the collection.

I've set the inputfield variable as an Object because you appear to be using late binding.