Excel VBA保护计算除以0

Jos*_*osh 1 excel vba excel-vba

我试图用基于简单除法的数据填充单元格但是(并且将永远是)在等式的一端或两端具有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
Run Code Online (Sandbox Code Playgroud)

以下是等式中引用的数据

P    Q      R    S
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
Run Code Online (Sandbox Code Playgroud)

谢谢你的期待!

use*_*756 5

我回答你的问题以及其他一些注意事项:

  • 你可以利用IfError() WorksheetFunction来捕获错误

  • If Range("H1").Value Like "*Mon*" Then在每次迭代中重复都是一个逻辑错误

    在开始时检查一次,然后相应地进行

  • 你可以counter通过偏移循环范围变量来避免变量

对于你可以编码的所有内容

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
Run Code Online (Sandbox Code Playgroud)