I am looking to copy and paste certain rows if conditions are met. If cell is blank, then skip to next row.
The code below is not skipping the blank cells, and is instead copying and pasting everything from Sheet1 to DataTable worksheet. Unsure why If Status <> "" is not filtering out the blanks.
Sub copypaste()
Dim Cell As Range
Dim CellCol As Range
Dim PasteCell As Range
Dim PasteCellAmount As Range
Dim DataTable As Worksheet
Set DataTable = Worksheets("Data")
Set CellCol = Sheet1.Range("C2:C50")
For Each Cell In CellCol
'paste cells into blank row
If DataTable.Range("A2") = "" Then
Set PasteCell = DataTable.Range("A2")
Set PasteCellAmount = DataTable.Range("C2")
Else
Set PasteCell = DataTable.Range("A2").Offset(1, 0)
Set PasteCellAmount = DataTable.Range("C2").Offset(1, 0)
End If
'copy cell in Column A and C in the row with value
If Cell <> "" Then
CellCol.Offset(0, -2).Copy PasteCell
CellCol.Offset(0, 0).Copy PasteCellAmount
Next cell
End sub
(1) Your code is missing an End If
statement (to close the last If
), so it won't compile.
(2) As you write CellCol.Offset(0, -2)
, you will always copy the whole CellCol
-Range ("C2:C50"). With other words: If at least one cell is not empty, the whole range is copied. If 30 cells are not empty, the range will copied 30 times, but that makes no difference.
What you (probably, I don't know your exact logic) need to do is use cell
:
cell.Offset(0, -2).Copy PasteCell
cell.Offset(0, 0).Copy PasteCellAmount
(3) You never change the destination cells. After the first copy, you will have to move to the next row (else every copy command will overwrite the previous). For example
cell.Offset(0, -2).Copy PasteCell
cell.Offset(0, 0).Copy PasteCellAmount
Set PasteCell = PasteCell.Offset(1, 0)
Set PasteCellAmount = PasteCellAmount.Offset(1, 0)