QP School

Full Version: Calculate factorial of a given number in VBA
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Example:

Function Factorial(number As Integer) As Double
    Dim result As Double
    Dim i As Integer

    result = 1

    'Calculate factorial
    For i = 1 To number
        result = result * i
    Next i

    Factorial = result
End Function

Sub CalculateFactorial()
    Dim num As Integer

    'Enter the number for which you want to calculate the factorial
    num = 5

    'Calculate and display the factorial using the Factorial function
    MsgBox "Factorial of " & num & " is: " & Factorial(num)
End Sub

Explanation:

The code defines a custom function named Factorial, which calculates the factorial of a given number.
The Factorial function takes an integer number as input and returns a Double as the result.
A variable result is initialized to 1, as the factorial of 0 is 1.
The For loop runs from 1 to number, and in each iteration, the result is multiplied by i.
The Factorial function returns the final result as the factorial of the input number.
The CalculateFactorial subroutine demonstrates how to use the Factorial function.
A number (5 in this example) is assigned to the variable num.
The factorial of num is calculated using the Factorial function and displayed in a message box using MsgBox.