Calculate factorial of a given number in VBA - Printable Version +- QP School (https://qomplainerzschool.lima-city.de) +-- Forum: Tutorials (https://qomplainerzschool.lima-city.de/forumdisplay.php?fid=3) +--- Forum: Excel VBA Tutorials (https://qomplainerzschool.lima-city.de/forumdisplay.php?fid=48) +--- Thread: Calculate factorial of a given number in VBA (/showthread.php?tid=5264) |
Calculate factorial of a given number in VBA - Qomplainerz - 07-27-2023 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. |