Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Calculate factorial of a given number in VBA
#1
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.
Also follow me on Youtube for videos about video games:
https://www.youtube.com/channel/UCxfkGVU...2mQ/videos
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Calculate the avg and color the cells when their values are above or below the avg Qomplainerz 0 429 07-27-2023, 10:41 AM
Last Post: Qomplainerz
  Calculate the sum of values in a column with VBA Qomplainerz 0 360 07-27-2023, 08:18 AM
Last Post: Qomplainerz
  Calculate the factorial of a number with VBA Qomplainerz 0 360 07-27-2023, 07:56 AM
Last Post: Qomplainerz
  Count the number of rows in a worksheet with VBA Qomplainerz 0 327 07-27-2023, 07:50 AM
Last Post: Qomplainerz
  Calculate the average of three numbers in VBA Qomplainerz 0 327 07-27-2023, 07:40 AM
Last Post: Qomplainerz
  How to format an entire column as number without thousand separator in Excel VBA Qomplainerz 0 459 04-13-2023, 12:26 PM
Last Post: Qomplainerz
  How to format an entire column as number with thousand separator in Excel VBA Qomplainerz 0 431 04-13-2023, 12:25 PM
Last Post: Qomplainerz

Forum Jump:


Users browsing this thread: 1 Guest(s)