HairyHippy
Programmer
I am trying to locate all cells with a particular colour and clear the contents of these cells. The following code just continues to loop, despite that only a small number of cells actually has the colour in question, in a test spreadsheet (spreadsheet I'm trying to apply this to has thousands of these specific cells). Here is the code:
Sub SelectByFormatAndClearContents()
'checks version of Excel to see if it can use FindFormat
If Val(Application.Version) < 10 Then
MsgBox "This requires Excel 2002 or later."
Exit Sub
End If
Dim FirstCell As Range, FoundCell As Range
Dim AllCells As Range
'specifies the format to look for
With Application.FindFormat.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ColorIndex = 36 'light yellow
End With
Set FirstCell = Cells.Find(What:="", SearchFormat:=True)
If FirstCell Is Nothing Then
MsgBox "No matching cells were found."
Exit Sub
End If
'initialise AllCells
Set AllCells = FirstCell
Set FoundCell = FirstCell
'loop until FirstCell is found again
Do
Set FoundCell = Cells.FindNext(After:=FoundCell)
Set AllCells = Union(FoundCell, AllCells)
If FoundCell.Address = FirstCell.Address Then Exit Do
Loop
'select cells found and clear the contents
AllCells.Select
Selection.ClearContents
End Sub
Sub SelectByFormatAndClearContents()
'checks version of Excel to see if it can use FindFormat
If Val(Application.Version) < 10 Then
MsgBox "This requires Excel 2002 or later."
Exit Sub
End If
Dim FirstCell As Range, FoundCell As Range
Dim AllCells As Range
'specifies the format to look for
With Application.FindFormat.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ColorIndex = 36 'light yellow
End With
Set FirstCell = Cells.Find(What:="", SearchFormat:=True)
If FirstCell Is Nothing Then
MsgBox "No matching cells were found."
Exit Sub
End If
'initialise AllCells
Set AllCells = FirstCell
Set FoundCell = FirstCell
'loop until FirstCell is found again
Do
Set FoundCell = Cells.FindNext(After:=FoundCell)
Set AllCells = Union(FoundCell, AllCells)
If FoundCell.Address = FirstCell.Address Then Exit Do
Loop
'select cells found and clear the contents
AllCells.Select
Selection.ClearContents
End Sub