My personal project this past week has been trying to parse a HTML table to Excel.
I've used many resources to finally get the code I'm looking for. It has taken a week to figure it out so I feel that I should share it to help others like me.
You may have problems if your website has frames. Use this:
Instead of:
Goodluck,
Paul
I've used many resources to finally get the code I'm looking for. It has taken a week to figure it out so I feel that I should share it to help others like me.
Code:
Sub ParseTable() Dim IE As InternetExplorer Dim htmldoc As MSHTML.IHTMLDocument 'Document object Dim eleColtr As MSHTML.IHTMLElementCollection 'Element collection for tr tags Dim eleColtd As MSHTML.IHTMLElementCollection 'Element collection for td tags Dim eleRow As MSHTML.IHTMLElement 'Row elements Dim eleCol As MSHTML.IHTMLElement 'Column elements Dim ieURL As String 'URL 'Open InternetExplorer Set IE = CreateObject("InternetExplorer.Application") IE.Visible = True 'Navigate to webpage ieURL = "Add URL here" IE.navigate ieURL 'Wait Do While IE.Busy Or IE.readyState <> 4 DoEvents Loop Set htmldoc = IE.document 'Document webpage Set eleColtr = htmldoc.getElementsByTagName("tr") 'Find all tr tags 'This section populates Excel i = 0 'start with first value in tr collection For Each eleRow In eleColtr 'for each element in the tr collection Set eleColtd = htmldoc.getElementsByTagName("tr")(i).getElementsByTagName("td") 'get all the td elements in that specific tr j = 0 'start with the first value in the td collection For Each eleCol In eleColtd 'for each element in the td collection Sheets("Sheet1").Range("A1").Offset(i, j).Value = eleCol.innerText 'paste the inner text of the td element, and offset at the same time j = j + 1 'move to next element in td collection Next eleCol 'rinse and repeat i = i + 1 'move to next element in td collection Next eleRow 'rinse and repeat End Sub
Code:
Set htmldoc = IE.document.frames.Item(x).document 'Replace x with the frame number that contains the table
Code:
Set htmldoc = IE.document
Paul
Comment