[英]Excel VBA On Error GoTo not working as intended
我正在使用 On Error GoTo 来捕获我的 function Linterp 的错误,它包含一个单元格和两个范围。 有时,Linterp 会抛出错误,在这种情况下,我只想将单元格设置为 5。但是,其他时候,当 Linterp 不抛出错误并正确返回预期数字(例如 3.25 或类似的数字)时,function仍然转到“案例 1”并将单元格设置回 5。
此外,尽管有人建议我在 On Error Goto 之后插入一个 Exit Sub,但我认为在我的特定情况下我不能这样做,因为我希望 function 继续遍历每个单元格,即使其中一个单元格正确执行了 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
在您的情况下,我更喜欢第一个解决方案。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.