Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
515 views
in Technique[技术] by (71.8m points)

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

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...