Language Translator | VBA

Recursive Factorial Calculation in VBA

This code snippet defines a VBA function that calculates the factorial of an integer using recursion, featuring a base case for termination and returning the accumulated result.


Empty image or helper icon

Prompt

Function Factorial(n As Integer) As Long
    If n <= 1 Then
        Factorial = 1
    Else
        Factorial = n * Factorial(n - 1)
    End If
End Function

Answer

VBA Code Translation

Original Code Snippet

The original code provided translates the concept of calculating the factorial of a number using recursion.

Code:

Function Factorial(n As Integer) As Long
    If n <= 1 Then
        Factorial = 1
    Else
        Factorial = n * Factorial(n - 1)
    End If
End Function

Explanation

  • Function Declaration: The function is named Factorial and returns a Long type.
  • Recursion: It checks if n is less than or equal to 1, returning 1 in that case (base case). If not, it recursively calls itself to calculate the factorial.

Translation to VBA

Since the provided code is already in VBA, no changes are needed. Below is the same code formatted correctly for clarity:

Translated Code:

Function Factorial(n As Integer) As Long
    If n <= 1 Then
        Factorial = 1
    Else
        Factorial = n * Factorial(n - 1)
    End If
End Function

Summary

  • The function Factorial computes the factorial of a given integer n.
  • It includes a base case and uses recursion to accumulate the factorial value.
  • The code is idiomatic to VBA and ready for immediate use.

Create your Thread using our flexible tools, share it with friends and colleagues.

Your current query will become the main foundation for the thread, which you can expand with other tools presented on our platform. We will help you choose tools so that your thread is structured and logically built.

Description

This code snippet defines a VBA function that calculates the factorial of an integer using recursion, featuring a base case for termination and returning the accumulated result.