Results 1 to 5 of 5

Thread: Need VBA code to display 1st PRIME number greater than value (N)

  1. #1

    Need VBA code to display 1st PRIME number greater than value (N)

    find the first PRIME number greater than a given number N. So for example, if N is 10 it should return 11, and if N is 24 it should return 29 (since 25-28 are not prime numbers.)

    Any help would be much appreciated, I'm not even sure where to start. Thank you.

  2. #2
    I'd start with doing something like this.

  3. #3
    Knowledge Base Approver VBAX Guru GTO's Avatar
    Sep 2008
    Hi Erik,

    I did not check any of the hits, but just had to comment... Tears, can't see, too funny!!!


  4. #4
    VBAX Wizard
    Apr 2007
    Is this for developing an algorithm (e.g. homework)? Is there a upper limit?

    Otherwise, the fastest way would be be to just load a list of the first 10,000 or so numbers and use =MATCH()

    1. Use [CODE] ....[/CODE ] Tags for readability
    [CODE]PasteYourCodeHere[/CODE ] -- (or paste your code, select it, click [#] button)
    2. Upload an example
    Go Advanced / Attachments - Manage Attachments / Add Files / Select Files / Select the file(s)
    (multiple files can be selected while holding Ctrl key) / Upload Files / Done
    3. Mark the thread as [Solved] when you have an answer
    Thread Tools (on the top right corner, above the first message)
    4. Read the Forum FAQ, especially the part about cross-posting in other forums

  5. #5
    VBAX Expert
    Aug 2004
    using what Erik posted (too funny), this is what I came up

    Private Function IsDecimal(Number) As Boolean
        Dim splitted() As String
        splitted = Split(Number, ".")
        If UBound(splitted) <> 0 Then
            IsDecimal = True
        End If
    End Function
    Private Function IsPrimeNumber(Number) As Boolean
        For i = 2 To Number - 1
            If IsDecimal(Number / i) = False Then
                IsPrimeNumber = False
                Exit Function
            End If
        Next i
        IsPrimeNumber = True
    End Function
    Public Function NextPrime(Number As Long) As Long
        Dim lCheckPrimeNumber As Long
        Dim bPrime As Boolean
        lCheckPrimeNumber = Number
            lCheckPrimeNumber = lCheckPrimeNumber + 1
            bPrime = IsPrimeNumber(lCheckPrimeNumber)
            If bPrime Then
                NextPrime = lCheckPrimeNumber
            End If
        Loop While Not bPrime
    End Function
    Last edited by JKwan; 06-05-2014 at 08:43 AM. Reason: made it better

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts