Excel VBA:错误处理中断中间代码

时间:2018-07-30 17:32:40

标签: excel vba excel-vba error-handling

代码循环遍历大量数据以执行计算。前两本工作簿进展顺利。第三本工作簿,突然出现错误处理中断-不再起作用。为什么?

1)Break on Unhandled Errors在选项中正确标记

2)每次错误处理后均出现On Error GoTo 0

3)这会在On Error Resume Next和On Error GoTo ErrHandler中中断。

我以为OERN仍然无视其他任何错误处理?

这是冗长的代码。我删除了几个变量定义来简化它。

amount = lastcolumn / 6
totalstrikes = 0
Do Until amount = 0
    currentcolumn = amount * 6 - 5
    i = 2
Do Until Sheets("Data").Cells(i, currentcolumn).Value = ""
    currentminute = Sheets("Data").Cells(i, currentcolumn).Value
    If oldminute <> 0 Then
    On Error GoTo ErrHandler
        If WorksheetFunction.MRound(currentminute - oldminute, 1 / 86400) >= 0.0007 Then
            'Do Stuff
        End If
5        End If
    On Error GoTo 0
        Do Until Sheets("Data").Cells(i, currentcolumn) <> currentminute
        If InStr(1, hitlist, Sheets("Data").Cells(i, currentcolumn + 1).Value) = False Then
            totaltime = totaltime + CSng(Sheets("Data").Cells(i, currentcolumn + 4).Value)
            totaltotal = totaltotal + CSng(Sheets("Data").Cells(i, currentcolumn + 2).Value)
        End If
        i = i + 1
    Loop
    On Error Resume Next
    If totaltime / totaltotal <= failuretime Then
        Strike = 1
    Else
        Strike = 2
    End If
    On Error GoTo 0
    If minute1 = 0 Then
        'do stuff with the minutes
    End If
    oldminute = currentminute
Loop
amount = amount - 1
Loop
Exit Sub
ErrHandler:
If WorksheetFunction.MRound((-1 * (currentminute - oldminute)), 1 / 86400) >= 0.0007 Then
    Resume Next
Else
    GoTo 5
End If
End Sub

先谢谢了。

1 个答案:

答案 0 :(得分:6)

您可以通过这种方式进行操作并管理运行时错误:

If WorksheetFunction.MRound(currentminute - oldminute, 1 / 86400) >= 0.0007 Then
    'Do Stuff
End If

...或者无需管理运行时错误,只需删除WorksheetFunction并测试该函数的返回值是否存在错误:

Dim m
m = Application.MRound(currentminute - oldminute, 1 / 86400)
If IsError(m) Then
    m = Application.MRound((-1 * (currentminute - oldminute)), 1 / 86400)
End If