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

非常新手的用户,有一些困难得到这个代码启动和运行。 我正在尝试计算一些基于其他单元格的值,并重复以最小化错误。 运行时,我得到了单元格(i,17)=单元格(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 

当你退出这个循环时, i的值实际上是表格中的行数+ 1导致的错误 – 你试图引用一个不存在的行。

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

 Dim i As Long i = Rows.Count 

说明:

 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 

这里的问题是, for循环将增加i超出Rows.Count 。 这意味着Cells(i, 17) = Cells(i, 5)实际上是指在电子表格结束之后的行。

通常情况下,我们不会在Next i之后使用Next i 。 通常,我们只使用ForNext之间的variables。 目前还不清楚你期望For...Next循环能达到什么效果,因为它们通常被用来执行一些代码多次,每次只是改变一个variables。

有一件事情你可能会觉得有用:你可以逐行使用F8逐行执行代码。 然后,你可以检查variables和其他东西,以确保它们是你所期望的。