我是VBA的初学者。我作为标题的问题,我真的不知道如何纠正代码。我正在尝试但我认为这一切都是错的......提前谢谢。
Sub Try_Click()
Dim i As Integer
Dim n As Integer
n = ThisWorkbook.Sheets("Sheet 1").Cells(3, 2).Value
For i = 1 To n
i = i * (i + 1)
Next i
ThisWorkbook.Sheets("Sheet 1").Cells(5, 2) = i
End Sub
答案 0 :(得分:3)
请勿在循环中更改 i :
Sub Try_Click()
Dim i As Long
Dim n As Long
Dim prod As Long
n = ThisWorkbook.Sheets("Sheet 1").Cells(3, 2).Value
prod = 1
For i = 1 To n
prod = prod * i
Next i
ThisWorkbook.Sheets("Sheet 1").Cells(5, 2) = prod
End Sub
答案 1 :(得分:2)
您需要添加另一个变量来计算它,如下所示:
Sub Try_Click()
Dim i As Integer
Dim n As Integer
Dim k As Long
k = 1
n = ThisWorkbook.Sheets("Sheet2").Cells(3, 2).Value
For i = 1 To n
k = k * (i)
Next i
ThisWorkbook.Sheets("Sheet2").Cells(5, 2) = k
End Sub
答案 2 :(得分:2)
结果需要一个额外的变量。因为如果您在i
循环中更改For
,则无法自动增加循环。
另外,我建议使用Long
代替Integer
(result
)。为什么?因为对于n > 7
,它已经超过Integer
的限制并抛出溢出错误。 Long
至少持续到n = 12
。要获得更多信息,您需要使用Double
,但这会产生n > 18
的近似结果。
Option Explicit
Sub MultiplyN()
Dim i As Long
Dim n As Long
n = 10 'ThisWorkbook.Sheets("Sheet 1").Cells(3, 2).Value
Dim result As Long
result = 1
For i = 1 To n
Debug.Print result & " *" & i & "=" 'look this output in the intermediate window
result = result * i
Next i 'auto increments i
Debug.Print result
'ThisWorkbook.Sheets("Sheet 1").Cells(5, 2) = result
End Sub
请注意,计算时不需要所有Debug.Print
行,只是为了在中间窗口中说明会发生什么。
答案 3 :(得分:2)
如评论中所述,我也会这样做:
Option Explicit
Public Sub Try_Click()
Dim n As Long
With ThisWorkbook.Sheets("Sheet 1")
n = .Cells(3, 2)
.Cells(5, 2) = Application.WorksheetFunction.Fact(n)
End With
End Sub
答案 4 :(得分:1)
如果您不想在单元格B5中使用公式,可以在VBA中使用@SJR建议:
=FACT(B3)
代码将是:
Sub Try_Click()
With ThisWorkbook.Sheets("Sheet 1").Cells(5, 2)
.FormulaR1C1 = "=FACT(R[-2]C)"
.Value = .Value
End With
End Sub