Monday, September 28, 2015

VBA sample code Prime number checker

This is a sample code to make a user form which checks if the number is prime or not. If you enter a number in the above box, it checks if it is a prime number. Open the Excel and make a UserFom as follows:

Note that you don't need to write "TextBox1" and "TextBox2" inside the boxes. I wrote them inside to make it easy to understand. Then write a code as follows:
-------------------------------------------------------------------------------
Private Sub UserForm_Initialize()

TextBox1.SetFocus
TextBox2.Value = "Enter a number above"

End Sub

Private Sub CommandButton1_Click()
If Not IsNumeric(TextBox1.Value) Then
    TextBox2.Value = "Enter only numbers."
    Exit Sub
End If

If IsPrime(CLng(TextBox1.Value)) Then
    TextBox2.Value = "This is a prime number."
ElseIf Not IsPrime(CLng(TextBox1.Value)) Then
    TextBox2.Value = "This is not a prime number."
End If

End Sub

Function IsPrime(ByVal number As Long) As Boolean

    If number > 3 Then
        If number Mod 2 = 0 Then Exit Function
        If number Mod 3 = 0 Then Exit Function
    End If
 
    Dim divisor As Long
    Dim increment As Long
    Dim maxDivisor As Long
 
    divisor = 5
    increment = 2

    maxDivisor = Sqr(number) + 1
 
    Do Until divisor > maxDivisor
        If number Mod divisor = 0 Then Exit Function
        divisor = divisor + increment

        increment = 6 - increment
    Loop
 
    IsPrime = True
 
End Function