VBA Prime数字用于循环获取"下一个没有用于"

时间:2014-08-05 12:31:32

标签: excel vba for-loop

我是编程和VBA的新手,想知道为什么这不起作用。我得到"下一个没有For error"。我已经找到了答案,但我并没有找到适合这个具体案例的任何答案。我的意思是," next"是"对于"。怎么能说,如果没有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

2 个答案:

答案 0 :(得分:1)

试试这个。我添加了评论来描述代码中的错误。

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

答案 1 :(得分:0)

您不需要尝试最多n-1的每个号码,您可以停在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