【问题标题】:Excel VBA On Error GoTo not working as intendedExcel VBA On Error GoTo 无法按预期工作
【发布时间】:2020-11-19 19:23:58
【问题描述】:

我正在使用 On Error GoTo 来捕捉我的函数 Linterp, 的错误,该函数包含一个单元格和两个范围。有时,Linterp 会抛出错误,在这种情况下,我只想将单元格设置为 5。但是,其他时候,当 Linterp 没有抛出错误并正确返回预期数字时,例如3.25 或类似的东西,该函数仍然转到“案例 1”并将单元格设置回 5。

此外,尽管this suggestion 我在 On Error Goto 之后插入了一个 Exit Sub,但我认为在我的特定情况下我不能这样做,因为我希望该函数继续遍历每个单元格,即使其中一个单元格在第一次尝试时正确执行 Linterp。

Sub Linterp_Test_1()
    For Each cell In Selection
        Set cell_index = Cells(3, "I")
        Set cell_xs = Range(Cells(cell.Row, "K"), Cells(cell.Row, "O"))
        Set cell_ys = Range(Cells(cell.Row, "D"), Cells(cell.Row, "H"))
        
        On Error GoTo Case1
        cell.Value = Linterp(cell_index, cell_xs, cell_ys)
        Resume Next
        
Case1:
        cell.Value = 5
        Resume Next
        
    Next cell
End Sub

【问题讨论】:

  • 发生错误时需要清除错误。您可能想查看THIS 您也不需要使用GoTo Case1。检查该帖子中On Error Resume Next 如何与If Err.Number <> 0 Then 一起使用...
  • 如果你能发布Linterp函数的代码就好了,因为使用范围不是很有效。

标签: excel vba error-handling goto


【解决方案1】:

错误处理

在你的情况下,我更喜欢第一个解决方案。

Option Explicit

Sub Linterp_Test_1()
    
    If TypeName(Selection) <> "Range" Then Exit Sub
    
    On Error Resume Next
    
    For Each cell In Selection
        
        Set cell_index = Cells(3, "I")
        Set cell_xs = Range(Cells(cell.Row, "K"), Cells(cell.Row, "O"))
        Set cell_ys = Range(Cells(cell.Row, "D"), Cells(cell.Row, "H"))
        
        cell.Value = Linterp(cell_index, cell_xs, cell_ys)
        If Err.Number <> 0 Then
            cell.Value = 5
            Err.Clear
        End If
    
    Next cell
    
    On Error GoTo 0
    
End Sub


Sub Linterp_Test_2()
    
    If TypeName(Selection) <> "Range" Then Exit Sub

    For Each cell In Selection
        
        Set cell_index = Cells(3, "I")
        Set cell_xs = Range(Cells(cell.Row, "K"), Cells(cell.Row, "O"))
        Set cell_ys = Range(Cells(cell.Row, "D"), Cells(cell.Row, "H"))
        
        On Error Resume Next
        cell.Value = Linterp(cell_index, cell_xs, cell_ys)
        If Err.Number <> 0 Then cell.Value = 5
        On Error GoTo 0
    
    Next cell
    
End Sub

【讨论】:

  • 我更喜欢第二个。第一个也会抑制其他不推荐的错误....
  • @SiddharthRout:谢谢。效率呢?真的有区别吗?如果没有,那么你是绝对正确的。
  • 在这种情况下,与忽略其他错误相比,我愿意牺牲效率:) 老实说,如果效率成为一个大问题,那么我将使用数组执行操作,然后写回工作表在 1 中 :)
  • 谢谢@VBasic2008 - 选项 1 工作得很好。 ?
  • 很高兴你喜欢它,但要小心,SiddharthRout 知道他在说什么。我已经介绍了这两种解决方案,因为我最近才完全理解错误处理。缺少的部分是: 1. 当On Error Goto 0 安全地处理它时,为什么我需要Err.Clear?让On Error Resume Next 始终保持“活跃”状态。 (On Error Goto 0 '如果关闭则关闭'。2.(与您的情况无关)关于ResumeResume Next 的谜团,其中Resume 继续与发生错误的同一行,例如,如果您打算更改一些值直到没有错误为止。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-18
  • 1970-01-01
相关资源
最近更新 更多