Search code examples
vbaexcelie-automation

Clicking a button in IE using VBA


I am using Excel VBA to try click a button on a site, here's the code from the site using inspect element:

<button class="_ah57t _84y62 _frcv2 _rmr7s">ClickHere</button>

And here's what i'm doing in VBA:

Sub testcode()
Dim ie As InternetExplorer
Dim html As HTMLDocument
Set ie = New InternetExplorer
ie.Visible = True
ie.Navigate "somesite.com"

Do While ie.READYSTATE <> READYSTATE_COMPLETE
DoEvents
Loop

Dim e
Set e = ie.Document.getElementsByClassName("_ah57t _84y62 _frcv2 _rmr7s")
e.Click

End Sub

Using the debug I found that the code seems to be storing something called "[object]" in the variable e and and then gives a Runtime error '438' when it gets to e.click. I have even tried using .Focus first, but get the same error. Any ideas?


Solution

  • The getElementsByClassName() function returns a collection not a single element. You need to specify an index on the returned collection in order to return a single element. If there is only one element within the class you can simply use:

    ie.Document.getElementsByClassName("_ah57t _84y62 _frcv2 _rmr7s")(0).Click
    

    The (0) specifies the index of the element within the collection returned from the class.

    Its easy to tell whether a function returns a collection or single element:

    • getElementBy... - Returns a single element.
    • getElementsBy... - Returns a collection of elements.