在VBA中错误溢出

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

 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 

原来有溢出的错误。 我在互联网上search,并找出它我的示例代码应该转换为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).ValueRange("N" & i).Value / Range("O" & i).Value )) 它作为parameter passing给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 

从这里得到NotNullOrZero函数由@BrianKE回答。