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
264 views
in Technique[技术] by (71.8m points)

How do I click a link on a web page using Excel VBA?

I'm writing VBA code to obtain a ticker symbol from a user, navigate to a website, input the ticker symbol and click the appropriate link.

I researched this StackOverflow question and response, however, I don't have an innertext value to utilize.

My VBA code:

Sub clicklick()
Dim ie As Object
Dim form As Variant, button As Variant
Set ie = CreateObject("InternetExplorer.Application")
ticker = InputBox("Enter Ticker Symbol: ")

With ie
.Visible = True
.Navigate ("http://www.SITE_URL.com")

While ie.ReadyState <> 4
DoEvents
Wend

ie.document.getElementsbyName("sSrchTerm").Item.innertext = ticker

End With
End Sub

The link appears as follows in the page source:

<a class="hqt_button" href="javascript:void(0): onclick=HeaderBox.trySubmit()"></a>

The element doesn't seem to have a name, innertext or id. How can I click the link?

EDIT:

    Set Link = ie.document.getElementsByTagName("a") 
    For Each l In Link 
        If Link.classname = "hqt_button" Then 
            Link.Click 
            Exit For 
        End If 
    Next l 
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Try getting the collection of anchor tags, with:

GetElementsByTagName("a")

Then, iterate that collection using as much logic as you can to ensure you're clicking the right button.

For each l in ie.document.getElementsByTagName("a") 
    If l.ClassName = "hqt_button" Then
        l.Click
        Exit For
    Next

If there are multiple anchors with the same classname, you could do:

    If l.ClassName = "hqt_button" AND l.Href = ""javascript:void(0): onclick=HeaderBox.trySubmit()" Then
        l.Click
        Exit For
    Next

Alternatively

If you are using IE9+ you could use the GetElementsByClassName method.

GetElementsByClassName("hqt_button")   

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

...