【问题标题】:Excel VBA run-time error 1004: Application-defined or object-defined errorExcel VBA 运行时错误 1004:应用程序定义或对象定义错误
【发布时间】:2016-09-02 22:45:14
【问题描述】:

非常新手用户,在启动和运行此代码时遇到了一些困难。我正在尝试根据其他一些单元格计算一个值并进行迭代以最小化错误。运行时,我在 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

【问题讨论】:

  • 设置Cells(i, 17) = Cells(i, 5)时你想做什么?将单元格Cells(i,17) 中的值设置为等于Cells(i, 5) 中的当前值?还有For Loop 在做什么?现在它在到达你的 iter 变量之前要经过整个循环,所以你的 for 循环的结果每次都会完全一样。

标签: excel vba runtime-error


【解决方案1】:

当您退出该循环时,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

【讨论】:

  • 关于i 如何在For ... Next 中增加的很好的捕捉和解释。
【解决方案2】:

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

通常,我们不会在Next i 之后使用i。通常,我们只使用ForNext 之间的变量。我不清楚您希望For...Nextloop 实现什么,因为它们通常用于多次执行某些代码,每次只更改一个变量。

您可能会发现有用的一件事:您可以使用F8 逐行逐行执行代码。然后您可以检查变量和其他内容,以确保它们符合您的预期。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多