简体   繁体   中英

VBA - Delete all rows after last row in copied data

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!

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM