如何解决这个溢出问题

时间:2018-03-12 09:47:11

标签: excel vba excel-vba

请问为什么第5行导致溢出?我检查数据的数据是0将超过0,我想这可能是问题,但我不确定,是否有任何解决方案可以使这项工作?

HKColumn = 2

Do Until Cells(6, HKColumn).Value = 0

    Cells(34, 27).Value = (Cells(6, HKColumn) - Cells(5, HKColumn)) / (Worksheets("TOTAL").Cells(6, HKColumn) - Worksheets("Total").Cells(5, HKColumn))
    Cells(34, 26).Value = "2018 " + Cells(3, HKColumn)
    Cells(34, 17).Value = (Cells(11, HKColumn) - Cells(10, HKColumn)) / (Worksheets("TOTAL").Cells(11, HKColumn) - Worksheets("Total").Cells(10, HKColumn))
    Cells(34, 16).Value = "2018 " + Cells(3, HKColumn)

    Cells(32, 27).Value = (Cells(5, HKColumn) - Cells(4, HKColumn)) / (Worksheets("TOTAL").Cells(5, HKColumn) - Worksheets("Total").Cells(4, HKColumn))
    Cells(32, 26).Value = "2017 " + Cells(3, HKColumn)
    Cells(32, 17).Value = (Cells(10, HKColumn) - Cells(9, HKColumn)) / (Worksheets("TOTAL").Cells(10, HKColumn) - Worksheets("Total").Cells(9, HKColumn))
    Cells(32, 16).Value = "2017 " + Cells(3, HKColumn)

    HKColumn = HKColumn + 1

Loop

1 个答案:

答案 0 :(得分:0)

如果所有值都为0,则会给出溢出,因为0/0在Excel中抛出溢出错误 - Why is 0 divided by 0 throwing an overflow error in VBA?

解决问题的两种方法:

  • 真的不推荐使用方法,这会强制VBA忽略每个错误 - 在代码顶部写On Error Resume Next。然后在底部写下On Error GoTo 0

  • 始终检查除数是否不等于0。这是编程中的标准,只要不允许除以0即可。因此,像这样的东西甚至使它成为一个单独的功能:

If (Cells(6, HKColumn) - Worksheets("Total").Cells(5, HKColumn))) <> 0 Then
        Cells(34, 27).Value = (Cells(6, HKColumn) - Cells(5, HKColumn)) / the-non-zero-val
End If