gpt4 book ai didi

vba - Excel VBA保护计算不被0除

转载 作者:行者123 更新时间:2023-12-04 21:08:27 26 4
gpt4 key购买 nike

我正在尝试使用基于简单除法的数据填充单元格,但在某些情况下(并且将永远存在)我在等式的一端或两端都有 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

以下是等式中引用的数据
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

感谢您的关注!

最佳答案

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

  • 你可以利用 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

    关于vba - Excel VBA保护计算不被0除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42120316/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com