-1

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

4

1 回答 1

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 可以显示多少材料是有限的。

于 2013-10-23T19:27:58.220 回答