I am reviewing your function once and you have a couple mistakes so far. I've been using VB for about 11 years now, and I will point them out to you, and post a bug free function.
You didn't post any information about how your function works. From what I can gather, the argument InNoWanted, will return the nth prime number, where n is the value of InNoWanted. For example, your function should produce the following results.
--------------------------------------
| InNoWanted | Value Returned |
--------------------------------------
| 1 | 2 |
--------------------------------------
| 2 | 3 |
--------------------------------------
| 3 | 5 |
--------------------------------------
| 4 | 7 |
--------------------------------------
The first error I have encountered is this that a value of zero will mess stuff up. You should add a check to make sure a value of zero is not entered:
CODE
Public Function GetPrimeNo(InNoWanted As Integer) As Long
Dim lPrimes() As Long
Dim lTrial As Long
Dim lCount As Integer
Dim lFound As Integer
Dim lCounter As Integer
If InNoWanted = 0 Then
Exit Function
End If
Nextly, it returns an error because you do not have enough elements in your array. You define 3 below this ReDim statement. Therefore you should add 3 to the amount of elements to create.
CODE
ReDim lPrimes(InNoWanted + 3)
You also commented out some code. You need that to have your program run correctly.
CODE
'Define the first three prime number
lPrimes(0) = 2
lPrimes(1) = 3
lPrimes(2) = 5
Other than that, you have no other programming mistakes in your code. Below is the fixed version:
CODE
Public Function GetPrimeNo(InNoWanted As Integer) As Long
Dim lPrimes() As Long
Dim lTrial As Long
Dim lCount As Integer
Dim lFound As Integer
Dim lCounter As Integer
If InNoWanted = 0 Then
Exit Function
End If
ReDim lPrimes(InNoWanted + 3)
lTrial = 5
lCount = 3
lFound = 0
'Define the first three prime number
lPrimes(0) = 2
lPrimes(1) = 3
lPrimes(2) = 5
Do
lTrial = lTrial + 2
lFound = 0
For lCounter = 0 To lCount - 1
lFound = (lTrial Mod lPrimes(lCounter)) = 0
If lFound Then
Exit For
End If
lCounter = lCounter + 1
Next lCounter
If lFound = 0 Then
lPrimes(lCount) = lTrial
lCount = lCount + 1
End If
Loop While (lCount < InNoWanted)
GetPrimeNo = lPrimes(InNoWanted - 1)
End Function
Reply