1

I'm new to programming and VBA and would like to know why this doesn't work. I get the "Next without For error". I have searched for answers, but I didn't really find any that fit this specific case. I mean, the "next" is to lines below the "for". How can it say, it would be a next without a for?

Private Sub Primerus_Click()

Number As Long, i As Long
Number = InputBox("Please enter a Number", "Math for Idiots", "Please enter your number here.")
For i = 2 To Number - 1
  If Number Mod i <> 0 Then
  Next i
  Else: MsgBox ("This is not a prime number")

End Sub
End If

MsgBox ("This is a prime number.")

End Sub
Alex K.
  • 171,639
  • 30
  • 264
  • 288
Shadol
  • 100
  • 2
  • 11
  • 1
    Your `for` and `if` aren't nested properly. It should be : `For .. If .. End if .. Next` (Next is the closing statement for the `for` loop. And you aren't suppose to have 2 `End sub`s. If you want to increment in the loop with a condition, use a [`while` loop](http://msdn.microsoft.com/fr-fr/library/zh1f56zs.aspx) instead. – Sifu Aug 05 '14 at 12:43
  • 1
    Karol Marian Słuszniak corrected your code but it will not work as it should - it will not find prime number. Take a look at this solution: http://www.excel-easy.com/vba/examples/prime-number-checker.html there is also more complicated case here: http://support.microsoft.com/kb/202782 – lowak Aug 05 '14 at 12:51

2 Answers2

1

Try this. I've added comments to describe what was wrong in your code.

Sub Primerus_Click()

    Dim Number As Long, i As Long

    Number = InputBox("Please enter a Number", "Math for Idiots", "Please enter your number here.")

    'for is the outer statment
    For i = 2 To Number - 1
        'if is nested in for
        If Not Number Mod i <> 0 Then
            MsgBox ("This is not a prime number")
            'you exit from a sub with "exit sub" not "end sub"
            Exit Sub
        'here you end your if
        End If
    'here you incriment i in your loop
    Next i

    MsgBox ("This is a prime number")

End Sub
Maco
  • 429
  • 13
  • 19
0

You don't need to try every number up to n-1, you can stop at n^0.5

Sub Primerus_Click()

    Dim i As Long, n as Long, prime As Boolean
    prime = True

    n = InputBox("Please enter a Number", "Math for Idiots", "Please enter your number here.")

    For i = 2 To Int(Sqr(n))
        If n Mod i = 0 Then
            prime = False
            Exit For
        End If
    Next

    MsgBox IIf(prime, "Prime number", "not prime number")

End Sub
z̫͋
  • 1,531
  • 10
  • 15
  • This is nor correct. You can stop at n/2, but not at n^0.5 Take 22. It can be divided by 11. – Shadol Aug 05 '14 at 13:35
  • 1
    @Shadol `22=11*2`, so the algorithm will find that `22` can be divided by `2`. See [Why do we check upto the square root of a prime number to determine if it is prime?](http://stackoverflow.com/questions/5811151/why-do-we-check-upto-the-square-root-of-a-prime-number-to-determine-if-it-is-pri) – z̫͋ Aug 05 '14 at 13:41