Excel VBA保护计算除以0
我正在尝试使用基于简单划分的数据填充单元格,但是有(并且将一直存在)实例,其中我在等式的一端或两端都有一个0。
是否有可能围绕等式进行某种保护,以便如果它除以0,则只将值设置为0,而不是出错?
我的代码
Set myRange = Range("S3:S20") rowCounter = 3 For Each myCell In myRange If Range("H1").Value Like "*Mon*" Then myCell.Value = Range("Q" & rowCounter).Value rowCounter = rowCounter + 1 Else myCell.Value = ((myCell.Value + Range("Q" & rowCounter).Value) / Range("R" & rowCounter).Value) rowCounter = rowCounter + 1 End If Next myCell
以下是等式中引用的数据
PQRS 5 1:03 5 1:03 0 0:00 0 0:00 0 0:00 0 0:00 7 0:19 7 0:19 0 0:00 0 0:00 0 0:00 0 0:00 12 0:26 12 0:26 3 0:15 3 0:15 3 1:16 3 1:16 7 0:29 7 0:29 9 0:14 9 0:14 0 0:00 0 0:00 0 0:00 0 0:00 6 0:28 6 0:28 0 0:00 0 0:00 4 0:15 4 0:15 0 0:00 0 0:00 0 0:00 0 0:00
感谢您的期待!
尝试下面的代码(检查列R = 0中的值)。
既然你正在循环与For Each myCell In myRange
,没有必要有另一个variables( rowCounter
)保持行号,只需使用myCell.Row
。
Option Explicit Sub HandleDev_ByZero() Dim myRange As Range, myCell As Range Set myRange = Range("S3:S20") For Each myCell In myRange If Range("H1").Value Like "*Mon*" Then myCell.Value = Range("Q" & myCell.Row).Value Else If Range("R" & myCell.Row).Value = 0 Then ' check if 0 myCell.Value = 0 Else myCell.Value = ((myCell.Value + Range("Q" & myCell.Row).Value) / Range("R" & myCell.Row).Value) End If End If Next myCell End Sub
我回答你的问题以及其他一些考虑因素:
-
您可以利用
IfError()
WorksheetFunction
来捕获错误 -
重复
If Range("H1").Value Like "*Mon*" Then
是一个逻辑错误If Range("H1").Value Like "*Mon*" Then
在每次迭代在开始时检查一次,然后相应地进行
-
您可以通过偏移循环范围variables来避免
counter
variables
所有以上你可以编码
Sub main() Dim myRange As Range, myCell As Range Set myRange = Range("S3:S20") If Range("H1").Value Like "*Mon*" Then myRange.Value = myRange.Offset(, -2).Value Else For Each myCell In myRange myCell.FormulaR1C1 = "=iferror((" & myCell.Value & "+ RC[-2])/RC[-1],0)" Next myCell myRange.Value = myRange.Value End If End Sub
那么如何检查列R中的值的额外的ElseIF语句 :
Set myRange = Range("S3:S20") rowCounter = 3 For Each myCell In myRange If Range("H1").Value Like "*Mon*" Then myCell.Value = Range("Q" & rowCounter).Value rowCounter = rowCounter + 1 ElseIf Range("R" & rowCounter).Value <> "0" Then myCell.Value = ((myCell.Value + Range("Q" & rowCounter).Value) / Range("R" & rowCounter).Value) rowCounter = rowCounter + 1 Else myCell.Value = 0 rowCounter = rowCounter + 1 End If Next myCell