Search code examples
htmlvbaweb-scrapingerror-handlinggetelementsbytagname

vba skip nonexisting elements from getElementsByTagName() to prevent error


I have this:

<table class="series">
    <tr><th>1.</th><td><div><a href="?test1">Link1</a></div></td></tr>
    <tr><th>2.</th><td><b>Link2</b></td></tr>
    <tr><th>3.</th><td><div><a href="?test3">Link3</a></div></td></tr>
</table>

and I need to loop through each in order to find where there is NO url link.

dim serieTest as Object
If element.tagName = "TABLE" And element.className = "series" Then
    Set data_series = element.getElementsByTagName("td")
    For Each serie In data_series
        Set serieTest = serie.getElementsByTagName("a")(0).href
        If Not (serieTest Is Nothing) Then
            debug.print "link found!"
        Else
            debug.print "link NOT found!"
        End If
        Set serieTest = Nothing
    Next
    Set data_series = Nothing
End If

but im having error:

Run-time error '91': Object variable or With block variable not set

on line with:

Set serieTest = serie.getElementsByTagName("a")(0).href

any idea how to prevent this? I have tried just to put On Error Resume Next above the errorline, but then it just goes straightly to "ELSE" as it doesnt asign anything so therefore "serie" i always null.


Solution

  • When you get an href value it is a string not an object. You could re-write your code as follows (though I would refer you to my prior answer to one of your questions which handles this scenario better using a helper function and select case):

    Dim serieTest As Object, serieHref As String
    
    If element.tagName = "TABLE" And element.className = "series" Then
    
        Set data_series = element.getElementsByTagName("td")
    
        For Each serie In data_series
    
            serieHref = "link NOT found!"
    
            If serie.getElementsByTagName("a").Length > 0 Then
    
                Set serieTest = serie.getElementsByTagName("a")(0) 'object
    
                If serieTest.hasattribute("href") Then
                    serieHref = serieTest.href
                    Debug.Print "link found!"
                End If
            End If
            Debug.Print serieHref
        Next
    
    End If