我想在VBA Excel中创建一个宏,它将生成所有素数等于或小于用户输入的列表...请给我一个想法,谢谢RS
答案 0 :(得分:0)
尝试一下:
Sub MAIN()
Dim ss As Single, i As Single
ss = Application.InputBox(Prompt:="Enter and integer", Type:=1)
k = 1
For i = ss To 1 Step -1
If IsPrime(i) Then
Cells(k, 1) = i
k = k + 1
End If
Next
End Sub
Function IsPrime(Num As Single) As Boolean
Dim i As Long
If Num < 2 Or (Num <> 2 And Num Mod 2 = 0) _
Or Num <> Int(Num) Then Exit Function
For i = 3 To Sqr(Num) Step 2
If Num Mod i = 0 Then Exit Function
Next
IsPrime = True
End Function
自:
http://dailydoseofexcel.com/archives/2005/06/30/is-this-number-prime/
修改#1 强>:
要使用MsgBox输出结果,请将其用于MAIN:
Sub MAIN()
Dim ss As Single, i As Single
Dim s As String
ss = Application.InputBox(Prompt:="Enter and integer", Type:=1)
k = 1
For i = ss To 1 Step -1
If IsPrime(i) Then
s = s & "," & i
End If
Next
MsgBox s
End Sub
但是MsgBox的显示材料数量有限。