VBA按行号删除特定行

时间:2018-01-16 21:30:08

标签: excel excel-vba vba

如果有人愿意帮助我,我将非常感激。

基本上我想执行与此线程中的功能相同的任务......

Excel Marcro - delete a row based on row number

我有一个3500多行的列表,需要根据行号偶尔删除大约25-30(非连续)行(行#s每次都会变化)。我想列出Sheet2上的行号(要删除)(在A列中),并让代码自动读取Sheet2上的行号并从Sheet1中删除这些行。我尝试了线程中提供的代码,我得到了一个“运行时错误424”对象。如果我将鼠标移到错误上,它会告诉我“SourceWks = Nothing”和“Sheet2 = Empty”。我确实有工作表中包含的数据。我确定我只是错过了一些简单的东西。

我将粘贴我正在使用的代码(再次来自用户报告的原始线程,以便正常工作)...

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

我已经尝试了两种方式......保持Sheet1名为“Sheet1”,Sheet2名为“Sheet2”,我也尝试将名称更改为:“deleteWKS”和“SourceWks”都使用相同的结果

如果有人可以请让我知道我做错了什么,我会非常感激。

1 个答案:

答案 0 :(得分:0)

考虑:

Sub rowKiller()

    Dim SourceWks As Worksheet, deleteWks As Worksheet
    Dim rng As Range, i As Long

    Set SourceWks = Sheet2
    Set deleteWks = Sheet1

    Set rng = SourceWks.Columns(1).SpecialCells(2)
    rng.Sort Key1:=rng(1), Order1:=xlDescending, Header:=xlNo, _
            OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
            DataOption1:=xlSortNormal

    For Each r In rng
        i = r.Value
        deleteWks.Rows(i).EntireRow.Delete
    Next r

End Sub

备注:

我们对行列表降序进行排序的原因是因为我们要从底部向上删除 Sheet1 中的行。