循环中的vba错误处理

jus*_*ess 18 error-handling vba

vba的新手,尝试'on error goto'但是,我一直在错误'索引超出范围'.

我只想制作一个组合框,其中包含一个包含查询表的工作表的名称.

    For Each oSheet In ActiveWorkbook.Sheets
        On Error GoTo NextSheet:
         Set qry = oSheet.ListObjects(1).QueryTable
         oCmbBox.AddItem oSheet.Name

NextSheet:
    Next oSheet
Run Code Online (Sandbox Code Playgroud)

我不确定问题是否与在循环中嵌套On Error GoTo或如何避免使用循环有关.

Gav*_*ith 23

问题可能是您没有从第一个错误中恢复.您不能在错误处理程序中抛出错误.您应该添加一个简历语句,如下所示,因此VBA不再认为您在错误处理程序中:

For Each oSheet In ActiveWorkbook.Sheets
    On Error GoTo NextSheet:
     Set qry = oSheet.ListObjects(1).QueryTable
     oCmbBox.AddItem oSheet.Name
NextSheet:
    Resume NextSheet2
NextSheet2:
Next oSheet
Run Code Online (Sandbox Code Playgroud)

  • 错误:恢复没有错误 (2认同)

Pat*_*rez 14

作为像示例代码一样处理循环错误的一般方法,我宁愿使用:

on error resume next
for each...
    'do something that might raise an error, then
    if err.number <> 0 then
         ...
    end if
 next ....
Run Code Online (Sandbox Code Playgroud)