excel表格Excel中计算阶乘(n!的VBA代码
2025-01-23 20:31:47
在Excel中可以通过FACT函数来计算非负整数n的阶乘(n!),而如果要通过VBA来计算阶乘,可以用下面的两个自定义函数:
1.使用循环:
Function Factorial_a(ByVal Num As Integer)
If Num < 0 Then
Factorial_a = "#NUM!"
Else
Factorial_a = 1
For i = 1 To Num
Factorial_a = Factorial_a * i
Next
End If
End Function
2.使用递归:
Function Factorial_b(ByVal Num As Integer)
If Num < 0 Then
Factorial_b = "#NUM!"
ElseIf Num = 0 Or Num = 1 Then
Factorial_b = 1
Else
Factorial_b = Num * Factorial_b(Num – 1)
End If
End Function