Consulting

Results 1 to 4 of 4

Thread: Factorial sub

  1. #1
    VBAX Newbie
    Joined
    Apr 2005
    Posts
    5
    Location

    Factorial sub

    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

  2. #2
    VBAX Master TonyJollans's Avatar
    Joined
    May 2004
    Location
    Norfolk, England
    Posts
    2,291
    Location
    Because the uninitialised value of an integer is zero.
    Enjoy,
    Tony

    ---------------------------------------------------------------
    Give a man a fish and he'll eat for a day.
    Teach him how to fish and he'll sit in a boat and drink beer all day.

    I'm (slowly) building my own site: www.WordArticles.com

  3. #3
    Distinguished Lord of VBAX VBAX Grand Master Bob Phillips's Avatar
    Joined
    Apr 2005
    Posts
    25,453
    Location
    Quote Originally Posted by anish201
    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
    ____________________________________________
    Nihil simul inventum est et perfectum

    Abusus non tollit usum

    Last night I dreamed of a small consolation enjoyed only by the blind: Nobody knows the trouble I've not seen!
    James Thurber

  4. #4
    Site Admin
    Urban Myth
    VBAX Guru
    Joined
    May 2004
    Location
    Oregon, United States
    Posts
    4,940
    Location
    anish201 - [uvba]here ya go[/uvba]

    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

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •