首页 > 解决方案 > VBA On Error GoTo 不工作

问题描述

我正在查看一个特定的 div 标签,如果没有 innerText,我想跳过它并转到 NextLink3。我认为当没有 innerText 但是,我只是得到一个运行时错误: subscript out of range at 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: 
...

标签: htmlvbaexcelweb-scraping

解决方案


Len()您可以在尝试使用该函数 拆分它之前检查以确保您的 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

推荐阅读