View Full Version : [SOLVED:] Factorial sub
anish201
05-18-2005, 01:12 AM
I am trying to write a sub to get the factorial of a number. From the code below, can someone tell me why I need to have the fac = 1 line before the For Next loop?
Sub factorial()
Dim fac As Integer, i As Integer, Num As Integer
Num = Range("a1").Value
fac = 1
For i = 1 To Num
fac = i * fac
Next i
Range("a2").Value = fac
End Sub
TonyJollans
05-18-2005, 01:32 AM
Because the uninitialised value of an integer is zero.
Bob Phillips
05-18-2005, 01:39 AM
I am trying to write a sub to get the factorial of a number.
Why do you have the need for this sub, Excel has a Fact worksheet function
=FACT(5)
If you want to do many in a batch, it would still be more efficient to call the worksheet function from VBA
Sub factorial()
Range("a2").Value = Application.Fact(Range("a1").Value)
End Sub
simpler and more efficient
Zack Barresse
05-18-2005, 04:07 PM
anish201 - here ya go
Also, guess I'll add my pence worth, as a Boolean UDF ...
Function ISFACTOR(lNum As Long, lFact As Long) As Boolean
ISFACTOR = Not CBool(lNum Mod lFact)
End Function
Powered by vBulletin® Version 4.2.5 Copyright © 2025 vBulletin Solutions Inc. All rights reserved.