首页 > Excel专区 > Excel教程 >

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

Excel教程 2021-11-13 11:28:05

 在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计算阶乘VBA代码

office教程网 Copyright © 2016-2020 https://www.office9.cn. Some Rights Reserved.