For example:
Dim IE As New SHDocVw.InternetExplorerMedium
Dim HTMLDoc As MSHTML.HTMLDocument
Dim col As New Collection, arr, id
IE.Visible = True
IE.navigate "website I am navigating to"
' waiting mechanism for website to load
arr = Array("longidname_1", "longidname_2", "longidname_3")
For Each id In arr
col.Add HTMLDoc.getElementById(id)
Next
I am not a very experienced coder, and I am trying to put to create a web-scraping tool that does not need to be very powerful/eloquent. My issue is that the only way I can scrape data off a specific website is by using each SHTMLelement’s id. I then want to put all of those element’s into one element collection, but I can’t figure out how to do this. Here is my code:
Dim IE As New SHDocVw.InternetExplorerMedium
Dim HTMLDoc As MSHTML.HTMLDocument
Dim HTMLgrades As MSHTML.IHTMLElementCollection ' The collection I want to make
Dim HTMLgrade1 As MSHTML.IHTMLElement
Dim HTMLgrade2 As MSHTML.IHTMLElement
Dim HTMLgrade3 As MSHTML.IHTMLElement 'there are 100's of grades, but I will just use three here
IE.Visible = True
IE.navigate "website I am navigating to"
' waiting mechanism for website to load
Set HTMLDoc = IE.Document
Set HTMLgrade1 = HTMLDoc.getElementById("longidname_1")
Set HTMLgrade2 = HTMLDoc.getElementById("longidname_2")
Set HTMLgrade3 = HTMLDoc.getElementById("longidname_3")
I have tried all types of code to add each element to the elementcollection, but I keep getting errors. I know there is most likely a super simple solution, so I appreciate any help I can get!
You can’t create and populate a from-scratch ElementCollection like that – you can only return one by querying the document where the query may return multiple elements (ie. getElementsByTagName vs. getElementById) If you want to collect the individual elements you can add them to a regular VBA Collection or maybe a scripting dictionary. FYI “I keep getting errors” is not a very useful way of telling us exactly what happens when you run your code.
Thank you Tim – that makes sense! Excuse the indefiniteness of the errors here – I didn’t want to bore everyone with the the myriad of methods I used and the errors they produced!