Excel宏 - 根据行号删除行

时间:2012-12-14 11:41:43

标签: excel vba

请帮助..我需要一个宏来删除基于行号(行号)的特定行,例如,如果我想删除第2行,第9行,第20行,第150行,如何在宏中完成,请提供一个宏,我可以在代码中复制和粘贴行号并从模块运行。我在sheet2列A中有行号,它们是要从sheet1中删除的行

1 个答案:

答案 0 :(得分:2)

一行:

Rows(4).Delete Shift:=xlUp

对于多行:

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

对于您的特定情况,允许根据源表中的行号列表动态删除行。将SourceWks更改为存储数字的工作表并将其删除到工作表中将删除行。

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