因子循环时的因子宏

时间:2016-09-05 10:23:13

标签: excel-vba macros vba excel

我正在尝试使用while循环编写一个开放的办公室宏代码来计算阶乘,但我发现它很难。到目前为止,我的代码。任何帮助都很高兴。

Sub DisplayFact()
    Dim n As Long
    Dim nFact As Long

    'Initialsing n to zero 
    if n = 0
        return nFact = 0 ;

    While n <= 4

        MsgBox "n = " & n & " ,  nFact =  " & nFact 

        n = n + 1
        nFact= n*nFact(n-1)
    Wend

End Sub

2 个答案:

答案 0 :(得分:0)

Sub DisplayFact()

    Dim n As Long

    n = 0 'Initialsing n to zero

    While n <= 4
        MsgBox "n = " & n & ", Fact = " & WorksheetFunction.Fact(n)
        n = n + 1
    Wend

End Sub

或者也许:

Do
.
.
Loop While n <= 4  

Do While n <= 4
.
.
.
Loop

答案 1 :(得分:0)

你应该使用For..To循环来做这种事情:

For n = 0 To 4
    MsgBox "n = " & n & " ,  nFact =  " & nFact 
    nFact= n * nFact(n - 1)
Next

此循环将以n开头,其值为0,并会在每次迭代时自动将n的值递增1。

您还可以使用可选的Step参数更改增量:

For n = 1 To 10 Step 2
    '// n will go through 1 > 3 > 5 > 7 > 9 and then exit
Next

For n = 10 To 1 Step - 3
    '// n will go through 10 > 7 > 4 > 1 and then exit
Next