Home » excel » excel – How to delete highlighted cells without indexing up?

excel – How to delete highlighted cells without indexing up?

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m trying to delete all cells that are highlighted yellow, leaving only the values that are not highlighted. However, every time I delete a highlighted cell, the cell directly below it indexes up into its place, because the value moves up into a different cell it is missed in the loop. Can I prevent cells below highlighted cells from indexing up?

Sub DeleteColoredCells()

    Dim Rng As Range
    Dim sCell As Range
    Set Rng = Range("A1:E4")
        For Each sCell In Rng
            If sCell.Interior.color = vbYellow Then
                sCell.Delete
            End If
        Next sCell
End Sub
How to&Answers:

Use this if you want to clear the formatting too. If you don’t instead of ClearContents use Clear

Sub DeleteColoredCells()

    Dim Rng As Range
    Dim sCell As Range
    Set Rng = Range("A1:E4")
        For Each sCell In Rng
            If sCell.Interior.color = vbYellow Then
                sCell.ClearContents
            End If
        Next sCell
End Sub