I want to use the code shown below to gain a better understanding of
how copy and paste work in VBA. When I run the code it gives me:
Run-time error '1004'
Application-defined or object-defined error
when it tries to execute
Cells(NextRow, 1).Select
At that point NextRow value is 6
The code is published at
https://msdn.microsoft.com/en-us/vba/excel-vba/articles/range-copy-method-excel
Ironically the code was provided by Bill Jelen,MrExcel.com!
The only intentional changes I made to the posted code (as far as I know) are: added Option Explicit; add Dim for variables; added a debug.print; changed the name of the source worksheet from sheet1 to SOURCE.
Please let me know how to avoid the error.
Thanks.
how copy and paste work in VBA. When I run the code it gives me:
Run-time error '1004'
Application-defined or object-defined error
when it tries to execute
Cells(NextRow, 1).Select
At that point NextRow value is 6
Code:
Public Sub CopyRows()
Sheets("SOURCE").Select
Dim FinalRow As Long
Dim x As Long
Dim ThisValue As String
Dim NextRow As Long
' Find the last row of data
FinalRow = Cells(Rows.Count, 1).End(xlUp).Row
' Loop through each row
For x = 2 To FinalRow
' Decide if to copy based on column D
ThisValue = Cells(x, 4).Value
If ThisValue = "A" Then
Cells(x, 1).Resize(1, 33).Copy
Sheets("sheetA").Select
NextRow = Cells(Rows.Count, 1).End(xlUp).Row + 1
Debug.Print "nextrow " & NextRow
Cells(NextRow, 1).Select
ActiveSheet.Paste
Sheets("SOURCE").Select
ElseIf ThisValue = "B" Then
Cells(x, 1).Resize(1, 33).Copy
Sheets("sheetB").Select
NextRow = Cells(Rows.Count, 1).End(xlUp).Row + 1
Cells(NextRow, 1).Select
ActiveSheet.Paste
Sheets("SOURCE").Select
End If
Next x
End Sub
The code is published at
https://msdn.microsoft.com/en-us/vba/excel-vba/articles/range-copy-method-excel
Ironically the code was provided by Bill Jelen,MrExcel.com!
The only intentional changes I made to the posted code (as far as I know) are: added Option Explicit; add Dim for variables; added a debug.print; changed the name of the source worksheet from sheet1 to SOURCE.
Please let me know how to avoid the error.
Thanks.