2015年3月7日 星期六

Access Excel VBA Check Prime Number using custom Function

This tutorial shows a custom Access Excel VBA Function that can check prime number, the Function returns TRUE or FALSE.


Access Excel VBA Check Prime Number using custom Function


In this tutorial, I will show a custom Access Excel Function that can check prime number, returning TRUE or FALSE. Prime number is an integer that can only be divided by 1 or itself (without remainder). Below are some examples of prime number.






















































































1–20235711131719232931374143475359616771
21–407379838997101103107109113127131137139149151157163167173
41–60179181191193197199211223227229233239241251257263269271277281
61–80283293307311313317331337347349353359367373379383389397401409

http://en.wikipedia.org/wiki/List_of_prime_numbers


Access Excel VBA Function Code – Check Prime Number


Public Function wIsPrimeNumber(sinput) As Boolean
    wIsPrimeNumber = True
    If sinput = 1 Then
        wIsPrimeNumber = False
    ElseIf sinput > 2 Then
        For i = 2 To sinput - 1
            If sinput Mod i = 0 Then
                wIsPrimeNumber = False
                Exit Function
            End If
        Next i
    End If
End Function

VBA Function Code Algorithm – Check Prime Number


Below is what I have done in the Function. This code is 100% original and I originally created it for a question posted in Microsoft Community. I did not even google for similar Function, let me know if you see any holes I am not aware of.


– Function wIsPrimeNumber returns TRUE or FALSE


– Function returns TRUE by default, unless it falls into IF criteria


– Divide the user input number by 1,2,3,…until number itself-1 , if no reminder for all the calculations, then it should be a prime number,  no action is needed because default is already TRUE (is prime number)


– Otherwise if any one of those calculations have no remainder, then it is not a prime number, and the Function returns FALSE


VBA Function Syntax – Check Prime Number


wIsPrimeNumber (sInput)

sInput is the number you want to check whether it is a Prime Number


Example – Check Prime Number












FormulaResult
=wisprimenumber(5)TRUE
=wisprimenumber(6)FALSE
=IF(wisprimenumber(5),”Prime Number”,”Not Prime Number”)Prime Number
=IF(not(wisprimenumber(5)),”Not Prime Number”,”Prime Number”)Prime Number

 



Access Excel VBA Check Prime Number using custom Function

沒有留言:

張貼留言