VBA 中的错误溢出

Error Overflow in VBA

我是 VBA 的新手。最近,我输入了一些代码,以下是我的代码示例:

Dim n As Long
n = Range("A1", Range("A1").End(xlDown)).Rows.Count
For i = 3 To n
Range("P" & i).Value = WorksheetFunction.IfError(Range("N" & i).Value / Range("O" & i).Value, 0))
Next

结果出现了Overflow的错误。我在网上搜索了一下,发现我的示例代码应该转换为Long类型的数据。然而,当我变成:

Range("P" & i).Value = CLng(WorksheetFunction.IfError(CLng(Range("N" & i).Value) / CLng(Range("O" & i).Value), 0))

问题依旧。

感谢您的帮助!

代码中的除法 (Range("N" & i).Value / Range("O" & i).Value) 之前发生,它作为参数传递给 IfError 函数。因此,如果除法失败,您的代码就会崩溃,并且 IfError 永远没有机会做任何事情。

另一种方法是:

Dim n As Long
n = Range("A1", Range("A1").End(xlDown)).Rows.Count
For i = 3 To n
    'Set the value in column P to a default value
    Range("P" & i).Value = 0
    'Switch on error handling
    On Error Resume Next
    'Attempt the calculation - if it fails, the value in column P will not change
    Range("P" & i).Value = Range("N" & i).Value / Range("O" & i).Value
    'Switch error handling off again
    On Error GoTo 0
Next

您可以检查单元格值是零还是空。如果没有,你可以进行计算。

Sub Demo()
    Dim n As Long
    n = Range("A1", Range("A1").End(xlDown)).Rows.Count
    For i = 3 To n
        If NotNullOrZero(Range("O" & i).Value) Then
            Range("P" & i).Value = WorksheetFunction.IfError(Range("N" & i).Value / Range("O" & i).Value, 0)
        Else
            Range("P" & i).Value = ""
        End If
    Next
End Sub

Public Function NotNullOrZero(aValue As Variant) As Boolean
    ' Returns true if the value is not null and greater than zero
    If Not IsNull(aValue) Then
       If (aValue > 0) Then
           NotNullOrZero = True
       End If
    End If
    NotNullOrZero = False
End Function

从@BrianKE 回答的 here 得到 NotNullOrZero 函数。