【问题标题】:Excel VBA: Error Handling Breaking Mid-CodeExcel VBA:错误处理中断中间代码
【发布时间】:2019-01-07 00:36:59
【问题描述】:

代码循环通过大量数据执行计算。适用于前两个工作簿。第三个工作簿,突然错误处理中断 - 不再有效。关于为什么的想法?

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

提前致谢。

【问题讨论】:

  • Err.Clear放在Resume Next之前。
  • 根据经验,如果在这么小的函数中有那么多On Error 语句,则需要考虑重构代码。过度依赖GoToResume 会导致代码意大利面,难以阅读和维护。

标签: vba excel error-handling


【解决方案1】:

您可以这样做并管理您的运行时错误:

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

【讨论】:

  • VBA 没有“Mround”功能不会打扰到任何人吗?正确的语法是Application.Worksheetfunction.Mround(... 或只是Worksheetfunction.Mround(...,而不是Application.Mround(...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多