Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

VBA proble to find the prime numbers between 1 and n numbers! Write a program th

ID: 3550472 • Letter: V

Question

VBA proble to find the prime numbers between 1 and n numbers!


Write a program that lists all the prime numbers in a user specified range. For this program, the user will enter an integer into an inputbox and this integer will serve as the upper value for the range of numbers to be investigated. Your program will then find every prime number within the range, and output these numbers to the spreadsheet. For instance, if the user enters 15, then the program will find and list all prime numbers in the rangeof1-15. Below is an example. Sample InputBox with user entered valueof15 Sample output for user input range from 1-15 Note that Cell Al contains the user specified range.

Explanation / Answer


Sub Macro1()
'
' Macro1 Macro
'

Dim count As Integer
Dim pos   As Integer


num = InputBox(Prompt:="Enter upper range of numbers", Title:="Enter number", Default:=" ")
Range("A1").Value = "Prime numbers in the range 1 to " & num
Range("A2").Value = "1"
pos = 3

For x = 1 To num
count = 0

For y = 1 To x
If ((x Mod y) = 0) Then
     count = count + 1
End If

Next y

If (count = 2) Then
Range("A" & pos).Value = x
pos = pos + 1
End If

Next x