从VBA中的errorhandler返回for循环

时间:2017-01-06 14:39:46

标签: excel excel-vba excel-2010 vba

如何从VBA中的Errorhandler返回for for循环?

for x = 1 to 1000
  On error goto errorhandler
  Sheets("Sheet1").Cells(x, "B") = x * Sheets("Sheet1").Cells(x, "A").Value
continue:
Next

Exit sub

Errorhandler:
  Sheets("Sheet1").Cells(x,"B") = "Error occured"
  Resume continue

这不起作用。我希望如果在for循环中发生错误,它将在单元格中写入"出现错误"然后继续循环。怎么做?

2 个答案:

答案 0 :(得分:2)

On Error GoTo Errorhandler 'put once, outside loop
    For x = 1 To 1000
    'use value2 if you dont work with date/time
        Sheets("Sheet1").Cells(x, "B").Value2 = x * Sheets("Sheet1").Cells(x, "A").Value2
    Next

    Exit Sub

Errorhandler:
    Sheets("Sheet1").Cells(x, "B").Value2 = "Error occured"
    Resume Next '<< Answer to original question. The Resume to continue label should also work

答案 1 :(得分:1)

我的代码在测试时有效,所以我不确定您遇到的具体问题,但是您可以考虑重构代码以避免GoTo语句,这将提高其可读性:

Sub foo()
Dim x As Long
Dim val

For x = 1 To 1000
    On Error Resume Next
    val = x * Sheets("Sheet1").Cells(x, "A").Value
    If Err.Number <> 0 Then
        Sheets("Sheet1").Cells(x, "B") = "Error occured"
    Else:
        Sheets("Sheet1").Cells(x, "B") = val
    End If
    On Error GoTo 0
Next


End Sub
相关问题