I am using vba in Excel to create a Macro. I have a for loop that cycles through all the rows and copies certain rows that match criteria to a new worksheet. Currently, the macro works, I have it copying the rows to the same row number, but this causes blanks rows to exists, which I get rid of. Is there a way to do this better by copying the row to after the last used row?
Here is my code:
' Set the lastRow variable
lastRow = Worksheets("Original").Cells.Find("*", [A1], , , xlByRows, xlPrevious).ROW
' The Total is in column K and the Class is in Column C
On Error Resume Next
For i = lastRow To 1 Step -1
' Check the columns for Total and Class values
If (Worksheets("Original").Cells(i, "K").Value2) <> 0 Then
Worksheets("Original").Rows(i).Copy Worksheets("NEW WS").Cells(i, 1)
'Worksheets("Original").Rows(i).Copy Worksheets("NEW WS").Cells(Worksheets("NEW WS").Rows.Count, col).End(xlUp).ROW
ElseIf ((Worksheets("Original").Cells(i, "K").Value2) = 0) Then
If (Worksheets("Original").Cells(i, "C").Value2) < 81 Or (Worksheets("Original").Cells(i, "C").Value2) > 99 Then
Worksheets("Original").Rows(i).Copy Worksheets("NEW WS").Cells(i, 1)
'Worksheets("Original").Rows(i).Copy Worksheets("NEW WS").Cells(Worksheets("NEW WS").Rows.Count, col).End(xlUp).ROW
End If
End If
Next i
Worksheets("NEW WS").Columns(1).SpecialCells(xlCellTypeBlanks).EntireRow.Delete
The commented lines:
Worksheets("Original").Rows(i).Copy Worksheets("NEW WS").Cells(Worksheets("NEW WS").Rows.Count, col).End(xlUp).ROW
Do not work. I am not sure why. Excel won't copy anything from the original worksheet to the new one at all when I try to use this code. How can I get it to work?