Original Post
I am fairly new to VBA and until now I managed to do everything. I am stuck at a "basic-looking" task, which is to copy a row from a sheet to another sheet, based by the background color of the cells. The background is done by conditional formatting and are only red if the values are out of tolerance.
I tried multiple things, couldn't do it with anything yet. Not even close.
My last try was with Cells.DisplayFormat.Interior.Color = vbRed
, but I couldn't manage the searching row-by-row. I also tried using for the For cycle AllRows = ActiveSheet.UsedRange.Rows.Count
so that it only goes to the last used row, but I got stuck pretty quickly.
If you can help me with this, I would appreciate it very much. If I missed any crucial part of the problem, please ask, I will gladly provide it.
Thanks!
Solution
Sub copy_formatted()
Dim startRange As Range
Dim copyRange As Range
Dim i As Long
Dim startOfRowCell As Range
Dim Cell As Range
' edit to the top left cell of the data area
Set startRange = Worksheets(2).Range("A5")
' edit to the top left cell of the area where you want to copy the rows
Set copyRange = Worksheets(1).Range("A5")
' variable for next empty row
i = 0
' Loop over all rows
For Each startOfRowCell In Worksheets(2).Range(startRange, startRange.End(xlDown))
' loop over all cells in row
For Each Cell In Worksheets(2).Range(startOfRowCell, startOfRowCell.End(xlToRight))
' check for formatting
If Cell.DisplayFormat.Interior.Color = vbRed Then
' copy whole row
Cell.EntireRow.copy
' paste to second table (only values, not the formatting)
copyRange.Offset(i, 0).PasteSpecial xlValues
' increment to paste next row beneath
i = i + 1
' break the inner loop to check next row if "red" value is found
Exit For
End If
Next Cell
Next startOfRowCell
End Sub