VBA – Function to write the divisors of a number
Yesterday I wrote an article for an Excel function, checking whether a specified number is prime or not.
Today I tought that it would be somehow a good idea to modify this function, in a way to check the number and if it is not prime to write down the divisors. Actually it was not very tough, as far as I have changed only a few lines of the code, making it a lot slower by removing the square root from the previous calculation. Anyway, the speed is not an issue, so enjoy the result from the routine “TestPrimeNumbers()” here:
The way the function works can be viewed here:

And finally the code. Find the 10 differences with the one from yesterday :
Option Explicit
Public Const cPrime As String = "Prime"
Public Const cNotPrime As String = "Not a prime, has other divisors."
Public Const cNotPositive As String = "A number should be an integer bigger than 0."
Public Function fDivisors(lNumber) As String
Dim i As Long
Dim bFirst As Boolean
If (lNumber = 1) Or (lNumber = 2) Or (lNumber = 3) Then
fDivisors = cPrime
Exit Function
End If
If (lNumber < 1) Or (lNumber <> CLng(lNumber)) Then
fDivisors = cNotPositive
Exit Function
End If
For i = 2 To (lNumber + 1) / 2 Step 1
If lNumber Mod i = 0 Then
If Not bFirst Then
fDivisors = i
Else
fDivisors = fDivisors & ", " & i
End If
bFirst = True
End If
Next i
If Len(fDivisors) < 1 Then fDivisors = cPrime
End Function
Public Sub TestPrimeNumbers(lStart As Long, lEnd As Long)
Dim i As Long
For i = lStart To lEnd Step 1
Debug.Print i & " " & fDivisors(i)
Next i
End Sub
Enjoy it! 🙂

