首页 > Excel专区 > Excel函数 >

Excel中计算阶乘(n!)的VBA代码

Excel函数 2022-02-13 20:34:54

在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


标签: 函数计算递归阶乘excel函数

office教程网 Copyright © 2016-2020 http://www.office9.cn. Some Rights Reserved. 苏ICP备20040415号-9