VBA Excel - 小于用户输入的质数列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19549736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 00:00:58  来源:igfitidea点击:

VBA Excel - List of Prime Numbers less than User Input

excel-vbavbaexcel

提问by R Sam

I want to make a macro in VBA Excel, that will generate list of all prime number equal or less than user input...Please give me the Idea, Thanks RS

我想在 VBA Excel 中制作一个宏,它将生成等于或小于用户输入的所有素数的列表......请给我想法,谢谢 RS

回答by Gary's Student

Give this a try:

试试这个:

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

From:

从:

http://dailydoseofexcel.com/archives/2005/06/30/is-this-number-prime/

http://dailydoseofexcel.com/archives/2005/06/30/is-this-number-prime/

EDIT#1:

编辑#1

To use a MsgBox to output the results, use this for MAIN:

要使用 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

But a MsgBox is limited in how much material they can display.

但是 MsgBox 可以显示的材料数量是有限的。