Calculate the factorial of a number with 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 the factorial of a number with VBA (/showthread.php?tid=5242) |
Calculate the factorial of a number with VBA - Qomplainerz - 07-27-2023 Example: Function Factorial(num As Integer) As Long Dim result As Long Dim i As Integer result = 1 For i = 1 To num result = result * i Next i Factorial = result End Function Sub CalculateFactorial() Dim num As Integer num = 5 'Enter the number for which you want to calculate the factorial MsgBox "The factorial of " & num & " is: " & Factorial(num) End Sub Explanation: This code consists of two parts. The first part defines a custom function named Factorial, which calculates the factorial of a given number. The second part defines a subroutine named CalculateFactorial, where you can specify the number for which you want to calculate the factorial. The custom function Factorial is created to calculate the factorial of a number. The function takes an integer input num and returns a Long value as the result. It uses a For loop to iterate from 1 to num and multiplies the numbers together to find the factorial. The CalculateFactorial subroutine calls the Factorial function with a specified number (num) and displays the factorial in a message box. |