0

me again , i am getting an issue with VBA resume function, my cobe below to check the number if it is primary number, it work fine for checking primary number , but when i put additonal code to try with another number , i got the issue (see the photo attach).

this is my code:

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

the error:

enter image description here

Could you please help look on this ? All assist will be appriciated :)

thangvc91
  • 323
  • 2
  • 10
  • Your `On Error GoTo error1` is not in the right place. It needs to come before the error happens. Also, you need to `Exit Sub` before the error handler part or it will run every time. Also, `Resume try_a_gain` belongs only in the error handler part, not your main routine. – braX Jul 15 '21 at 04:37

1 Answers1

0

You were not far wrong. It should look like this:

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

Differences: 1) Move the On Error to the start of the routine; 2) When the message box to try again is shown after a successful attempt, there has not been an error, so you cannot use Resume, you need to use GoTo instead (same applies to your value test); and 3) You should have an Exit Sub before your error trap.

Jonathan Willcock
  • 5,012
  • 3
  • 20
  • 31