在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