Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Calculate the factorial of a number with VBA
#1
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.
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 factorial of a given number in VBA Qomplainerz 0 257 07-27-2023, 11:04 AM
Last Post: Qomplainerz
  Calculate the avg and color the cells when their values are above or below the avg Qomplainerz 0 273 07-27-2023, 10:41 AM
Last Post: Qomplainerz
  Calculate the sum of values in a column with VBA Qomplainerz 0 247 07-27-2023, 08:18 AM
Last Post: Qomplainerz
  Count the number of rows in a worksheet with VBA Qomplainerz 0 231 07-27-2023, 07:50 AM
Last Post: Qomplainerz
  Calculate the average of three numbers in VBA Qomplainerz 0 224 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 358 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 330 04-13-2023, 12:25 PM
Last Post: Qomplainerz

Forum Jump:


Users browsing this thread: 1 Guest(s)