Home » excel » Excel VBA – For Loop Need To Skip First Element In Web Scrape

Excel VBA – For Loop Need To Skip First Element In Web Scrape

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m fairly new/inexperienced at VBA and I’m (seemingly) one small step from finishing a project that been kicking my butt. For some background, I’m scraping a website and navigating to the appropriate “tbody” tag and iterating through the encompassed “tr” tags. In each tr I am expecting two “td” cells. The problem is the first tr has a “th” tag with a colspan of 2, meaning obviously there is only one child in that tr and the code crashes out. What I don’t (yet) know how to do is to skips or account for the exception in the first tr. Here is the relevant snippet of the code:

R = 1

For Each ele In IE.Document.getElementsByTagName("tbody")(13).getElementsByTagName("td")


WSW.Range("H" & R).Value = ele.Children(0).textContent
WSW.Range("I" & R).Value = ele.Children(1).textContent

R = R + 1

Next

Not sure if I’ve walked myself down a rabbit hole, if the code is salvageable, or if the slate for this section of the code should be recreated. Thank you for any help.

How to&Answers:

The index of getElementsByTagName is zero to n based but the count (aka .length) is one to n based. You use R as the index reference so it does double duty.

dim R as long
R = 1

For R=1 to  IE.Document.getElementsByTagName("tbody")(13).getElementsByTagName("td").length -1

    with IE.Document.getElementsByTagName("tbody")(13).getElementsByTagName("td")(R)
        WSW.Range("H" & R).Value = .Children(0).textContent
        WSW.Range("I" & R).Value = .Children(1).textContent
    end with

Next R