How to Check for Prime Number in Excel VBA?

In this post, you’ll learn what prime number is and how to check for prime number in your excel workbook using Excel VBA.

Prime Numbers

A prime number is a number that has exactly two distinct divisors, i.e., 1 and itself. The numbers which are divisible by multiple divisors along with 1 and by itself are not prime numbers.

Example for prime numbers: 2,3,5,7

Example for Non-prime numbers: 4, 6, 8,9,10

How to Check for Prime Number in Excel VBA?

To check for Prime numbers using Excel VBA,

Code:


Sub CheckForPrime():

Dim divisors As Integer, number As Long, i As Long

divisors = 0

number = InputBox("Enter a number")

For i = 1 To number

If number Mod i = 0 Then

    divisors = divisors + 1

End If

Next i

If divisors = 2 Then

    MsgBox number & " is a prime number"

Else

    MsgBox number & " is not a prime number"

End If

End Sub

Result:

How to Check for Prime Number in Excel VBA?
How to Check for Prime Number in Excel VBA?
How to Check for Prime Number in Excel VBA?

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this post, you’ll learn how to Find Blank cells in excel so that you can remove or delete the blank cells form...
In this article, you’ll learn what is a Gauge Chart in Microsoft Excel. Also, you will learn how to add...
Microsoft Excel provides a shortcut for the users to move columns in excel using two different ways – using Shift...