VBA错误GoTo无法正常工作

时间:2018-08-09 15:18:00

标签: html excel vba excel-vba web-scraping

我正在查看一个特定的div标记,如果没有innerText,我想跳过它并转到NextLink3。我认为,当没有innerText时,我只会遇到运行时错误:test = arr(LBound(arr))的下标超出范围,并且我不确定如何处理。我以为“ On Error GoTo”将查看下一行是否产生错误,如果发生,则转到其他地方,但是我的以下代码没有做到这一点,并且仍然出现下标错误。

HTML代码:

<div style="width: 555px; -ms-overflow-x: auto; -ms-overflow-y: hidden;">
 <a href="/kegg-bin/ddi_list?drug=D00550">
  <img name="DDI" align="middle" onmouseover="btn(this,'DDIbh')" onmouseout="btn(this,'DDIb')" onmousedown="btn(this,'DDIbd')" onmouseup="btn(this,'DDIb')" ontouchstart="btn(this,'DDIbd')" ontouchend="btn(this,'DDIb')" alt="Drug interaction" src="/Fig/bget/button_DDIb.gif" border="0">
 </a>
</div>

我的VBA代码:

Dim ele As Object, test As String
Set ele = html.querySelectorAll(".td50 div")(3)
    If Not ele Is Nothing Then
        On Error GoTo NextLink3
        arr = Split(ele.innerText, Chr$(10))
        On Error GoTo NextLink3
        test = arr(LBound(arr))
        If InStr(arr(LBound(arr)), "[HSA") = 0 Or InStr(arr(LBound(arr)), " [KO") = 0 Then GoTo NextLink3
        For i = LBound(arr) To UBound(arr)
            Debug.Print Split(arr(i), "[")(0)
        Next i
        GoTo NextLink
    End If

NextLink3: 
...

1 个答案:

答案 0 :(得分:1)

在尝试使用Len()函数拆分html元素之前,您只需检查以确保其html元素具有值。

如果例如NextLink3仅用于处理我们现在要避免的错误,那么我不能确定不再需要哪个其他代码。

Dim ele As Object, test As String
Set ele = HTML.querySelectorAll(".td50 div")(3)

If Not ele Is Nothing Then

    If Len(ele.innerText) > 0 Then

        On Error GoTo NextLink3
        arr = Split(ele.innerText, Chr$(10))
        On Error GoTo NextLink3        'probably not necessary unless you call ... Goto 0 in NextLink3
        test = arr(LBound(arr))

        If InStr(arr(LBound(arr)), "[HSA") = 0 Or InStr(arr(LBound(arr)), " [KO") = 0 Then GoTo NextLink3

        For i = LBound(arr) To UBound(arr)
            Debug.Print Split(arr(i), "[")(0)
        Next i

        GoTo NextLink

    End If

End If