excel - 如何在 VBA 中模拟 Python "continue"语句的错误 AKA 中进行下一次迭代?

标签 excel vba

在下面的代码中,遇到错误后如何使循环在下一次迭代中继续 - 而不是下一行?

现在代码不会超过 x=0:

Sub skip_iteration()

Dim x As Long

For x = 5 To -5 Step -1
    On Error GoTo errhandler:
    Debug.Print 15 / x
    Debug.Print "I don't want this to be printed on error"
Next x

errhandler:
If Err.Number = 11 Then
    Debug.Print ("Error on " & x)
End If

End Sub

我研究过这个答案: Skip to next iteration in loop vba等,但无法将其转换为我的代码。

最佳答案

您需要Resume Next 转到该行之后的下一行,从而导致错误。 Err.Clear 也是一个很好的做法。

errhandler 之前的 Exit Sub 也是一个很好的做法:

Sub SkipIteration()

    Dim x As Long        
    For x = 5 To -5 Step -1
        On Error GoTo errhandler:
        Debug.Print 15 / x
        Debug.Print "testing"
    Next x        
    Exit Sub

errhandler:
    If Err.Number = 11 Then
        Debug.Print ("Error on " & x)
        Err.Clear
        Resume Next
    End If    
End Sub

ResumeResume Next 之间的区别如下:

  • Resume 尝试返回到调用它的位置。

TestMeResume 过程中,它在 Debug.Print a/b 处抛出错误 11,并在错误处理程序中分配 b = 5。然后使用 Resume 重试Debug.Print a/b,只要 b 不是 0,它就会运行。

  • Resume Next 转到调用它的位置,忽略该行并继续下一行。

TestMeResumeNext 过程中,在 a = 12 处抛出错误 91,并触发错误处理程序。在错误处理程序中,a 被分配给 Range("A14"),并且通过 Resume Nexta = 12 被跳过,并且 继续。


Sub TestMeResumeNext()

    On Error GoTo TestMeResumeNext_Error

    Dim a As Range
    a = 12              'Error 91 here!
    Debug.Print a.Row   'Resume Next goes back here
    Exit Sub

TestMeResumeNext_Error:
    Set a = Range("A14")
    Resume Next
End Sub

Sub TestMeResume()

    On Error GoTo TestMeResume_Error

    Dim a As Long: a = 10
    Dim b As Long: b = 0
    Debug.Print a / b   'Error 11 here the first time
    Exit Sub

TestMeResume_Error:
    b = 5
    Resume
End Sub

关于excel - 如何在 VBA 中模拟 Python "continue"语句的错误 AKA 中进行下一次迭代?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52857125/

相关文章:

Excel vba 创建范围的所有可能组合

mysql - 如果文本框为空,则将其设置为空

c# - microsoft.interop.excel 格式化单元格

vba - Excel循环遍历列表,转置并根据单元格内容创建矩阵

ms-access - MS Access 中的奇怪行为

excel - VBA - 使用单元格值名称更改目录文件夹

VBA - 尝试将递增数字添加到 Excel 单元格

vba - 如何删除某个工作表之后的工作表?

vba - Excel VBA 运行时错误 1004 : Application defined or object defined error

excel - ScreenUpdating是否有必要写成True