Search code examples
vbaexcelruntime-errorexcel-2007

VBA : Delete rows using variables


I wanted to delete rows from 2 to z (z > 2). I wrote 2 methods but neither worked. I searched for answers but didn't find a solution.

'.Rows("2:" & z).Select  
.Range(Cells(2, 1), Cells(z, 10)).Select  
Selection.Delete Shift:=xlUp

Thank you in advance.


Solution

  • You need to specify you want to select the rows with EntireRow, as your range is only a few cells :

    .Range(.Cells(2, 1), .Cells(z, 10)).EntireRow.Delete Shift:=xlUp
    

    Or cleaner ways if you directly use Rows :

    .Range(.Rows(2), .Rows(z)).Delete Shift:=xlUp
    

    Or

    .Rows("2:" & z).Delete Shift:=xlUp