#DIV / 0!错误并将其替换为零

时间:2018-02-14 17:43:15

标签: excel vba excel-vba compiler-errors

我正在尝试以下代码来检测DIV / 0错误并将其替换为零或空单元格。但**行给我一个错误

Dim Cell As Range
Dim iSheet as Worksheet
For Each iSheet In sheets(Array("Sheet1", "Sheet2", "Sheet3"))
    With iSheet
        For Each Cell In .UsedRange
            **If Cell.Value = CVErr(xlErrDiv0) Then Cell.Value = 0**
        Next Cell
    End With
Next iSheet

1 个答案:

答案 0 :(得分:2)

在将其与错误值

进行比较之前,您似乎必须检查cell.Value是否为错误
If IsError(Cell.Value) Then If Cell.Value = CVErr(xlErrDiv0) Then Cell.Value = 0

所以你的代码变成了

Sub mm()
    Dim Cell As Range
    Dim iSheet As Worksheet
    For Each iSheet In Sheets(Array("Sheet1", "Sheet2", "Sheet3"))
        With iSheet
            For Each Cell In .UsedRange
                If IsError(Cell.Value) Then If Cell.Value = CVErr(xlErrDiv0) Then Cell.Value = 0
            Next Cell
        End With
    Next iSheet
End Sub

限制细胞环的另一种可能性如下

Sub mm()
    Dim Cell As Range
    Dim iSheet As Worksheet

    For Each iSheet In Sheets(Array("Sheet1", "Sheet2", "Sheet3"))
        With iSheet
            If WorksheetFunction.CountIf(.UsedRange, "#DIV/0!") Then ' if any Division error found in current sheet used range cells
                For Each Cell In .UsedRange.SpecialCells(xlCellTypeFormulas, xlErrors) 'loop through error cells only
                    If Cell.Value = CVErr(xlErrDiv0) Then Cell.Value = 0
                Next
            End If
        End With
    Next
End Sub