I have a large workbook with many products, including specs, pricing and assorted calculation. When a product expires I'd like to move it to a EOL-sheet so I keep a log of old products.
This script should look at the selected rows, move the content to sheet "EOL", delete it from the original sheet, and skip all hidden rows.
It works if I select one cell, however if I select more cells, it doesn't correctly iterate through the full range.
Sub MoveRows()
Call SpeedUp
Dim SourceSheet As Worksheet
Dim TargetSheet As Worksheet
Dim LastRow As Long
Dim rng As Range
Set rng = Selection
Set SouceSheet = ActiveSheet
Set TargetSheet = ActiveWorkbook.Sheets("EOL")
TargetRow = ActiveCell.row
LastRow = TargetSheet.Cells(TargetSheet.Rows.Count, "D").End(xlUp).row + 1
For Each row In rng.Rows
If row.Rows.Hidden Then
TargetRow = TargetRow + 1
Else
ActiveSheet.Rows(TargetRow).Copy
TargetSheet.Rows(LastRow).PasteSpecial xlPasteFormulasAndNumberFormats
TargetSheet.Rows(LastRow).PasteSpecial xlPasteFormats
Rows(TargetRow).EntireRow.Delete
LastRow = LastRow + 1
End If
Next row
Call SpeedDown
End Sub
Note: the SpeedUp/SpeedDown function is to turn off screnupdating etc. for efficiency. Doesn't affect the script itself.
As I tested it commenting out the delete function, it copied the first cell repeatedly, obviously since TargetRow didn't change.
When I added TargetRow = TargetRow + 1
after the End If
it works.
When I uncomment the delete part, it doesn't work as I would expect.
As TargetRow is deleted, then I would think that the next row would be the new TargetRow, but it seems this doesn't happen.
I guess my problem is that there is no direct link between TargetRow and the iteration of rng.Rows.
How can I solve this? Is there a way to store all the moved rows in a list and subsequently delete them through a new iteration? Or maybe that is a bit too "python-thinking" for VBA?