2017-04-17 210 views
0

我是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 

而事实证明,有溢出的错误。我在互联网上搜索并找出它,我的示例代码应该被转换为Long类型的数据。但是,当我改成:

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

问题也依然存在。

谢谢你的帮助!

回答

2

该部门在您的代码(Range("N" & i).Value/Range("O" & i).Value)正在发生之前它是作为参数传递给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 
+0

它真的帮助我。谢谢。 –

1

您可以检查电池值是否是零或空。如果不是,你可以执行你的计算。

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 

here通过@BrianKE回答得到NotNullOrZero功能。

+1

非常感谢你! –