反向循环删除行-VB

时间:2019-06-06 07:57:42

标签: excel vba

我有一个数据集,其中包含有关客户的大量信息。我希望在将Yes输入到行K的单元格中并且将包含要从第一个工作表中删除的信息的原始行中输入Private Sub UpdateSheet2_Click() Dim c As Range Dim Source As Worksheet Dim Target As Worksheet 'Change worksheet designation as needed Set Source = ActiveWorkbook.Worksheets("Sheet1") Set Target = ActiveWorkbook.Worksheets("Sheet2") For Each c In Source.Range("K:K") 'Covers all rows If c = "yes" Then Source.Range("A" & c.Row & ":B" & c.Row).Copy Target.Range("A" & Rows.Count).End(xlUp).Offset(1, 0) Source.Range("D" & c.Row & ":F" & c.Row).Copy Target.Range("C" & Rows.Count).End(xlUp).Offset(1, 0) Source.Range("H" & c.Row & ":J" & c.Row).Copy Target.Range("F" & Rows.Count).End(xlUp).Offset(1, 0) End If ' If c = "yes" Then ' Source.Rows(c.Row).EntireRow.Delete ' End If Next c For i = 500 To 1 Step -1 If Source.Range("K" & i) = "yes" Then Source.Rows(i.Row).EntireRow.Delete End If Next i End Sub 到另一个工作表中

我正在按下按钮。工作正常,并且行被删除,但是当然,当它删除行时,行号向上移动一个,因此下一行被跳过(删除行15,然后行16变为行15,依此类推),所以我想出了一个反向循环是可行的方法,但是我无法一生解决这个问题-我认为这很简单!这是我正在使用的代码:

Source.Rows(i.Row).EntireRow.Delete

我现在只是将行号设置在1到500之间,当基本功能正常运行时,我将对其进行更改。您可以在For Each循环中看到我注释掉原始删除方法的位置。我目前在第.main-list行上出现错误“ Object required”

1 个答案:

答案 0 :(得分:3)

通常一次删除所有行效率更高。

Set c = Nothing 'reset your range
For i = 1 To 500 'or 500 To 1 Step -1 - doesn't make a difference
    If Source.Range("K" & i) = "yes" Then
        If c Is Nothing Then
            Set c = .Cells(i, 1).EntireRow 'if the range is empty then set it to the required row
        Else
            Set c = Union(c, .Cells(i, 1)).EntireRow 'otherwise add this row
        End If
    End If
Next
If Not c Is Nothing Then c.Delete xlUp 'if the range is not empty then delete all the rows

(我应该补充一点,我对Cells(x,y).EntireRow的使用纯粹是个人喜好。我总是使用该格式,因为我发现它更易于调试。)

相关问题