0

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?

Exam Orph
  • 365
  • 9
  • 18
  • 1
    No joke, this exact question gets asked at least once every day. Did you look at related questions? Error 438 means `e` doesn't have a `Click` (or `Focus`) method. – Mathieu Guindon Jun 09 '17 at 14:23
  • Apologies, as I didn't mean to add to the list of 'similar questions'. I searched the error as well as similar problems but couldn't figure out why it wasn't working...The click method applied to the variable e as you mention wasn't the problem, the problem was as per the bellow answer - the 's' at the end of elements! I think I need to get my eyes checked!!! – Exam Orph Jun 09 '17 at 15:02
  • For the record it *was* the problem. `e` being a *collection of elements* means `e` doesn't have a `Click` method. Otherwise you wouldn't have been getting run-time error 438 "Object does not support property or method" - that's what the error message means. – Mathieu Guindon Jun 09 '17 at 15:05

1 Answers1

2

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.
Jordan
  • 4,424
  • 2
  • 18
  • 32
  • Thank you so much, my eyesight must be giving in as I looked over this code so many times and only just noticed the 's' after you mentioned it! Feel kinda silly now! Thanks again. – Exam Orph Jun 09 '17 at 14:58
  • It's a very common issue! Glad I could help. – Jordan Jun 09 '17 at 15:07