VBA基于一定条件清除细胞范围

时间:2017-05-15 21:07:43

标签: vba clear cells

这个问题可能看起来很简单,但我现在已经处理了2天而且无法完成它。我搜索其他论坛,看看他们是否有同样的问题,但没有发现接近tyhis。 所以我从第2行开始有范围K:T,需要清除包含#N / A的单元格。我在下面编写了代码,但似乎无法使其正常工作。

Sub Clear_cells()
    Dim rng As Range, i As Integer

    'Set the range to evaluate to rng.
    Set rng = Range("K:T")

    'Loop backwards through the rows
    'in the range that you want to evaluate.
    For i = rng.Rows.count To 1 Step -1

        'If cell i in the range contains an "N/A", delete cell content
        If rng.Cells(i).Value = "#N/A" Then rng.Cells(i).CellRange.ClearContents (1)
    Next
End Sub

2 个答案:

答案 0 :(得分:0)

使用函数isna检查#N / A

 If Application.WorksheetFunction.IsNa(rng.Cells(i)) Then rng.Cells(i).CellRange.ClearContents (1)

答案 1 :(得分:0)

如果您的单元格包含错误值(即#N/A)而不是字符串"#N/A",那么您需要检查错误值而不是检查字符串。

替换

For i = rng.Rows.count To 1 Step -1

    'If cell i in the range contains an "N/A", delete cell content
    If rng.Cells(i).Value = "#N/A" Then rng.Cells(i).CellRange.ClearContents (1)
Next

Dim cel As Range
For Each cel in rng
    If IsError(cel.Value) Then
        If cel.Value = CVErr(xlErrNA) Then cel.ClearContents
    End If
Next

或者,如果要检查所有错误条件(例如#DIV/0!),只需使用

Dim cel As Range
For Each cel in rng
    If IsError(cel.Value) Then cel.ClearContents
Next