发布网友 发布时间:2024-09-27 08:01
共1个回答
热心网友 时间:2024-10-06 03:17
在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