Search code examples
vbainterfacecom

Why would a method work successfully in VBA even though it's not listed in the object library under the specific class?


In VBA I have the Microsoft HTML add in referenced. I'm declaring a variable as an IHTMLelement object. From there, I can still use the .getelementsbyclassname method without getting a syntax error despite the fact that this is not listed under the possible methods for the IHTMLelement class. There are several other variables for which this is an acceptable method, but I don't understand why it would work for this one

Sub overflowquestion()

'Turn on References to Microsoft Internet Controls and Microsoft HTML 

'Object Library before running

Dim IE As New InternetExplorer, el As IHTMLElement, sl As IHTMLElement

IE.navigate "www.youtube.com"

Do While IE.readyState <> 4

    DoEvents

Loop

Set el = IE.document.getElementsByClassName("skip-nav")(0)

'Why does this next line work?

Set sl = el.getElementsByClassName("masthead-search-terms-border")(0)


End Sub

Solution

  • There are a number of things to understand here.

    el is not an instance of an interface IHTMLElement it is an instance of a class Element which implements the IHTMLElement interface. Classes can implement multiple interfaces. The Element class may have inherited from another class, and it may implement several other interfaces, one of these classes/interfaces has the method getElementsByClassName

    As noted by Paulo Madeira in the comments, VBA is capable of late binding (see the docs for an overview of Interfaces, Classes, late an early binding) so it will try calling the method on the object whether the interface says it can or not.