I need to find and press a button on a webpage using VBA

Michaeljwjr picture Michaeljwjr · Jun 19, 2013 · Viewed 31.5k times · Source

I have written a macro that will open a webpage, find the spots I need to put the data into, and then I want the macro to hit a prefill button, then hit Ok.

The page source code for the button is:

<input type="text" size="30" maxlength="40" name="name" id="name">
<input type="button" value="Prefill" onclick="prefill()">

I've been searching for answers all week and I think I have a basic understanding of how this is supposed to work by running a loop to search for it, but I'm having no luck in my endeavor of actually getting this to work.

Can someone show me the loop that will search my page for this button?

Thank you in advance.

Requested code so far

Private Sub Populate_Click()
    Dim i As Long
    Dim IE As Object
    Dim objElement As Object
    Dim objCollection As Object

    Set IE = CreateObject("InternetExplorer.Application")

    IE.Visible = True
    IE.Navigate "website" 'make sure you've logged into the page

    Do
        DoEvents
    Loop Until IE.READYSTATE = 3

    Do
        DoEvents
    Loop Until IE.READYSTATE = 4
    ActiveSheet.EnableCalculation = False
    ActiveSheet.EnableCalculation = True
    Call IE.document.getelementbyid("name").SetAttribute("value", ActiveSheet.Range("b2").Value)
    Call IE.document.getelementbyid("aw_login").SetAttribute("value", ActiveSheet.Range("a2").Value)

    Set objCollection = IE.document.getElementsByTagName("input")
    i = 0
    While i < objCollection.Length
        If objCollection(i).Type = "button" And _
            objCollection(i).Name = "Prefill" Then
                Set objElement = objCollection(i)
        End If
        i = i + 1
    Wend
    objElement.Click
End Sub

Answer

Rick picture Rick · Jun 19, 2013

Looks like you are pretty close, this is what I have used to do something similiar

    With ie.document

        Set elems = .getelementsbytagname("input")
        For Each e In elems
            If (e.getattribute("className") = "saveComment") Then
                e.Click
                Exit For
            End If
        Next e

    End With

You will probably just have to change the if statement.

I also notice that your code refers to .Name = "Prefill" but your html snippet refers to .value = "Prefill"