Excel 用于循环获取的VBA素数;下一步不带“for”;
我是编程和VBA新手,想知道为什么这不起作用。我得到了“下一个没有错误”。我一直在寻找答案,但我没有真正找到任何适合这个具体案例的答案。我的意思是,“下一步”是指“for”下面的行。它怎么能说,这将是一个没有为下一个Excel 用于循环获取的VBA素数;下一步不带“for”;,excel,vba,for-loop,Excel,Vba,For Loop,我是编程和VBA新手,想知道为什么这不起作用。我得到了“下一个没有错误”。我一直在寻找答案,但我没有真正找到任何适合这个具体案例的答案。我的意思是,“下一步”是指“for”下面的行。它怎么能说,这将是一个没有为下一个 Private Sub Primerus_Click() Number As Long, i As Long Number = InputBox("Please enter a Number", "Math for Idiots", "Please enter your numb
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
Private Sub Primerus\u Click()
数字一样长,我一样长
数字=输入框(“请输入数字”、“傻瓜数学”、“请在此处输入数字”)
对于i=2到数字-1
如果数模i为0,则
接下来我
Else:MsgBox(“这不是质数”)
端接头
如果结束
MsgBox(“这是一个素数。”)
端接头
试试这个。我添加了注释来描述代码中的错误
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
Sub Primerus\u Click()
暗数一样长,我一样长
数字=输入框(“请输入数字”、“傻瓜数学”、“请在此处输入数字”)
“因为那是最外面的车站
对于i=2到数字-1
'if嵌套在for中
如果不是数字Mod i 0,则
MsgBox(“这不是质数”)
'您使用“退出子系统”而不是“结束子系统”退出子系统'
出口接头
“在这里,你结束了你的假设
如果结束
“在这里,你证明我在你的圈子里
接下来我
MsgBox(“这是一个素数”)
端接头
您不需要尝试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
您的
for
和if
嵌套不正确。它应该是:For。。如果。。如果..结束。。下一步
(下一步是for
循环的结束语句。你不应该有2个End sub
s。如果你想在循环中增加一个条件,请使用a。Karol Marian słuszniak更正了你的代码,但它不会正常工作-它不会找到素数。看看这个解决方案:还有更多这里的复杂情况:这也不正确。您可以在n/2处停止,但不能在n^0处停止。取22。它可以被11除。@Shadol22=11*2
,因此算法会发现22
可以被2
除。请参阅