Search code examples
vbainternet-explorerautomationie-automation

Tracking HTML Element Class With VBA


I have been searching the web for an answer but couldn't find anything useful so far. Question is as simple as the title actually. I have some elements in a web page and I would like my macro to perform actions only when they have/not have a specific class.

To be more precise these items are getting hidden with a hidden class added to them whenever you move within the page and as they still can be found getelementbyid I am kind of out of option to verify if this element is visible (hidden class is removed) or not.

I don't think any code needed? It is just some simple elements toggling hidden class and I am curious if I can check it with vba.

Thanks a lot in advance!


Solution

  • I figured I'd flesh it out for you in an answer, as the comment I left isn't all too informative.

    Set IE = CreateObject("InternetExplorer.Application")
    Dim URL as String
    URL = 'your URL here
    
    Dim HTMLdoc As HTMLDocument
    
    With IE
        .Silent = True
        .Visible = True
        .Navigate URL
    
        Do Until .readyState = 4
            DoEvents
        Loop
    
        Set HTMLdoc = .Document
    End With
    
    Dim hiddenElements As HTMLElementCollection
    Set hiddenElements = HTMLdoc.getElementsByClassName("your class name") 'add this to a watch or inspect your locals
    'Alternatively, you can print them all to the immediate window
    Dim hiddenElement as Variant
    For Each hiddenElement in hiddenElements
        Debug.Print hiddenElement.Value 'or .innerHTML or whatever you want here
    Next hiddenElement
    

    This works well if you're stepping through code, but using HTMLDocument and readyState can be cumbersome with realtime updating of the webpage, so MSXML.XMLHTTP60 is preferred..