Excel VBA运行时错误1004:应用程序定义的错误或对象定义的错误

1 excel vba runtime-error

非常新手用户,在启动和运行此代码时遇到一些困难.我试图根据其他一些单元格计算一个值并迭代以最小化错误.运行时,我在Cells(i,17)= Cells(i,5)行上得到上述错误.思考?谢谢.

Private Sub CommandButton1_Click()
Dim i As Long
A = 6.112
B = 17.67
C = 243.5
epsilon = 0.622
G = B * C
maxerror = 0.001
For i = 2 To Rows.Count
Next i
iter = 0
Cells(i, 17) = Cells(i, 5)

    Do While iter < 50
        iter = iter + 1
        bt = B * Cells(i, 17)
        tpc = Cells(i, 17) + C
        d = (Cells(i, 9) / A) * Exp(-bt / tpc)
        dm1 = d - 1#
        f = (Cells(i, 5) - Cells(i, 17)) - Cells(i, 16) * (epsilon / dm1 - Cells(i, 13))
        df = -G / (tpc * tpc)
        df = d * df * Cells(i, 16) * epsilon / (dm1 * dm1) - 1#
        cor = f / df
        Cells(i, 17) = Cells(i, 5) - cor
        If Abs(cor) < maxerror Then
            Exit Do
        End If
    Loop


End Sub
Run Code Online (Sandbox Code Playgroud)

Sam*_*Sam 5

退出该循环时,值i实际上是工作表+1中导致错误的行数 - 您尝试引用不存在的行.

如果你想要工作表中的最后一行,只需使用:

Dim i As Long
i = Rows.Count
Run Code Online (Sandbox Code Playgroud)

说明:

For i = 1 To 10
    Debug.Print i '// Prints 1,2,3,4,5,6,7,8,9,10 as expected
Next i '// When i = 10 and gets to this line, it still
       '// increases the value before it exits the loop

Debug.Print i '// Prints 11
Run Code Online (Sandbox Code Playgroud)