嵌套循环无法正常运行

时间:2015-08-24 08:15:41

标签: excel vba excel-vba

This is the output of the code. It removed all reference errors except for this cell我有一个嵌套循环,首先使用for循环将所有ref单元格更改为白色字体,然后在sub for循环中删除ref单元格。代码运行但仍有一个或两个具有引用错误的单元格。需要帮助来整理代码,以便它可以删除所有引用错误而不是大多数!谢谢。

Sub Delete_ref_basedontextcondition()
    Dim R As Range
    Dim w As Long, ref As Range
    Dim refi As Range
    On Error Resume Next
    'Set rng = Nothing
    On Error Resume Next
        Set R = Application.InputBox("Select cells To be deleted", Type:=8)
        Dim rng As Range
        If TypeName(R) <> "Range" Then
            Exit Sub
        Else
            R.Delete
        End If
        For w = 1 To Worksheets.Count
            With Worksheets(w)
                For Each ref In .Cells.SpecialCells(xlCellTypeFormulas, xlErrors)
                    If ref.Text = "#REF!" Then
                        ref.Font.ColorIndex = 2
                        For Each refi In .Cells.SpecialCells(xlCellTypeFormulas, xlErrors)
                            If refi.Text = "#REF!" Then
                                refi.Delete
                            End If
                        Next refi
                    End If
                Next ref
            End With
        Next w
End Sub

1 个答案:

答案 0 :(得分:0)

我相信流氓#REF!实际上是由refi.Delete创建的,因此在创建之前定义的循环会错过它。请改用refi.Clear。你只想删除不好的公式;你不想删除单元格并在其周围移动其他单元格(从而产生新的#REF!错误。)

把它想象成一个装满#REF的Pez饮水机!错误。每当你弹出一个,另一个进来代替它。使用.Clear关闭盖子,而不是通过.Delete弹出它们。