Reputation: 313
I am trying to figure out the code to delete all the rows after the last row of my copied data
I am copying data from worksheet A to worksheet B. Worksheet B already has data in it. if the number of rows in worksheet A is less than worksheet B, I want to delete all the rows that were not copied into worksheet B from worksheet A.
EG: Worksheet A = 50 Rows Worksheet B = 60 Rows. I copy Worksheet A to worksheet B, I want to delete the 10 Rows that were not part of Worksheet A.
Here is my code so far:
Dim shCurrentWeek As Worksheet
Dim shPriorWeek As Worksheet
Dim lr3 As Long
Set shCurrentWeek = ActiveWorkbook.Sheets("Current Week")
Set shPriorWeek = ActiveWorkbook.Sheets("Prior Week")
lr3 = shPriorWeek.Range(Rows.Count, "A").End(xlUp).Row
'Copies necessary rows in CurrentWeek tab to PriorWeek tab
shCurrentWeek.Range("A4:X" & lr).Copy shPriorWeek.Range("A2")
shPriorWeek.Range("A4:X" & lr3 + 1 & ":A" & Rows.Count).EntireRow.Delete
I am relatively sure my lr3 is set wrong... not sure how to fix.
thanks!
Upvotes: 0
Views: 4767
Reputation: 19544
Since your code says that shCurrentWeek.Range("A4:X" & lr).Copy shPriorWeek.Range("A2")
(In other words, you're copying from [starting row 4] to [starting row 2]) you could just forget about lr3
and do the following (I believe):
shCurrentWeek.Range("A4:X" & lr).Copy shPriorWeek.Range("A2")
shPriorWeek.Range("A" & lr-2 & ":A10000").EntireRow.Delete
Hope this helps
Upvotes: 2
Reputation: 3678
you want lr3
to be the row number of the last row (not the offset compared to your pasted data:
lr3 = shPriorWeek.Rows.Count
Then the delete statement should read:
shPriorWeek.Range("A4:A" & lr3).EntireRow.Delete
Alternatively first clearing THEN pasting (as suggested in the comments) is a good way as well, and very clean.
Upvotes: 1