Excel Marcro - delete a row based on row number [c

2019-07-21 12:29发布

please help..i need a macro to delete specific rows based on row number (line number) for example, if i want to delete the the 2nd,9th,20th,150th rows, how it can be done in macro, please provide a macro where i can copy and paste the line numbers in the code and run from module. i have the row numbers in sheet2 Column A which are the rows to be deleted from sheet1

标签: excel vba
1条回答
闹够了就滚
2楼-- · 2019-07-21 12:50

for one row:

Rows(4).Delete Shift:=xlUp

For multiple rows:

Union(Rows(4), Rows(7)).Delete Shift:=xlUp

For your specific case to allow to dynamically delete rows based on a list of row numbers in a source sheet. Change SourceWks to the worksheet where the numbers are stored and deletedWks to the worksheet where the rows are going to be deleted.

Dim deleteRows As Range
Dim data() As Variant
Dim i As Double

Dim SourceWks As Worksheet, deleteWks As Worksheet

Set SourceWks = Sheet2
Set deleteWks = Sheet1

    With SourceWks
        data = .Range(.Cells(1, 1), .Cells(1, 1).End(xlDown))
    End With

    Set deleteRows = deleteWks.Rows(data(1, 1))

    For i = 2 To UBound(data, 1)

        Set deleteRows = Union(deleteRows, deleteWks.Rows(data(i, 1)))

    Next i

    deleteRows.Delete Shift:=xlUp
查看更多
登录 后发表回答