【问题标题】:VBA - unable to call Resume [duplicate]VBA - 无法调用 Resume [重复]
【发布时间】:2021-07-15 04:25:49
【问题描述】:

再次,我遇到了 VBA 恢复功能的问题,我的 cobe 在下面检查号码是否是主号码,它可以正常检查主号码,但是当我输入附加代码尝试使用另一个号码时,我得到了问题(见附图)。

这是我的代码:

Sub check_pri()
    Dim flag As Boolean
    Dim i As Long: i = 2
    Dim value As Variant
    
try_a_gain:
    value = InputBox("input value")
    flag = True
    If value = "" Or value < 2 Then
        Resume try_a_gain
    End If
    For i = 2 To value - 1
        If value Mod i = 0 Then
            flag = False
            Exit For
        End If
    Next i
        If flag = True Then
            MsgBox value & " is pri number "
        Else
            MsgBox value & " is not pri number "
        End If
    yes = MsgBox("wanna try ? ", vbYesNo)
    If yes = vbYes Then
    Resume try_a_gain
    End If
    
    
    On Error GoTo error1
error1:
    MsgBox "error found"

     yes = MsgBox("wanna try ? ", vbYesNo)
    If yes = vbYes Then
    Resume try_a_gain
    End If
End Sub

错误:

你能帮忙看看这个吗?所有协助都将得到应用:)

【问题讨论】:

  • 您的On Error GoTo error1 不在正确的位置。它需要在错误发生之前出现。此外,您需要在错误处理程序部分之前Exit Sub,否则它将每次运行。此外,Resume try_a_gain 仅属于错误处理程序部分,而不属于您的主程序。

标签: vba


【解决方案1】:

你并没有大错特错。它应该是这样的:

Sub check_pri()
    Dim flag As Boolean
    Dim i As Long: i = 2
    Dim value As Variant
    
    On Error GoTo error1
    
try_a_gain:
    value = InputBox("input value")
    flag = True
    If value = "" Or value < 2 Then
        GoTo try_a_gain
    End If
    For i = 2 To value - 1
        If value Mod i = 0 Then
            flag = False
            Exit For
        End If
    Next i
        If flag = True Then
            MsgBox value & " is pri number "
        Else
            MsgBox value & " is not pri number "
        End If
    yes = MsgBox("wanna try ? ", vbYesNo)
    If yes = vbYes Then
        GoTo try_a_gain
    End If
    Exit Sub
    
error1:
    MsgBox "error found"

    yes = MsgBox("wanna try ? ", vbYesNo)
    If yes = vbYes Then
        Resume try_a_gain
    End If
End Sub

区别: 1) 将 On Error 移到例程的开头; 2) 尝试成功后出现重试消息框时,并没有报错,所以不能使用Resume,需要使用GoTo代替(同样适用于你的值测试);和 3) 你应该在错误陷阱之前有一个 Exit Sub。

【讨论】:

  • 谢谢兄弟 :) 。我已经解决了我的问题
猜你喜欢
  • 1970-01-01
  • 2014-04-22
  • 2022-01-21
  • 2015-03-24
  • 2013-01-08
  • 1970-01-01
  • 2014-09-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多