如果单元格G =“ YES”,则删除整行

时间:2019-03-16 12:44:48

标签: excel vba delete-row

hi,如果列G =“ YES”中的单元格有删除整个行的代码。它工作正常,但是当将单元格从一个工作簿复制到另一个工作簿时,它将删除粘贴的最后一行。就像我拖动单元格以自动填充一样。

Private Sub Worksheet_Change(ByVal Target As Range)
On Error Resume Next
Application.EnableEvents = False
'If Cell that is edited is in column U and the value is completed then
If Target.Column = 7 And Target.Value = "YES" Then
    'Define last row on completed worksheet to know where to place the row of data
    LrowCompleted = Sheets("EQUIP. OFF RENT").Cells(Rows.Count, "A").End(xlUp).Row
    'Copy and paste data
    Range(Target.Row & ":" & Target.Row).Copy Sheets("EQUIP. OFF RENT").Range("A" & LrowCompleted + 1)
   End If
   If Target.Column = 7 And Target.Value = "YES" Then

    Range(Target.Row & ":" & Target.Row).Delete
    End If

Application.EnableEvents = True

1 个答案:

答案 0 :(得分:0)

分析代码后,On Error Resume NextApplication.EnableEvents = False结合使用是一个经典问题。 即使代码中有错误,作业仍在运行。这就是例如在粘贴后删除最后一个单元格的原因。

为避免这种情况,我只需清除下一个错误简历和enableevents,然后在第一个If语句之前添加以下行:

If Target.Column = 1 Then Exit Sub

所以请尝试:

Private Sub Worksheet_Change(ByVal Target As Range)

If Target.Column = 1 Then Exit Sub

If Target.Column = 7 And Target.Value = "YES" Then
    'Define last row on completed worksheet to know where to place the row of data
    LrowCompleted = Sheets("EQUIP. OFF RENT").Cells(Rows.Count, "A").End(xlUp).Row
    'Copy and paste data
    Range(Target.Row & ":" & Target.Row).Copy Sheets("EQUIP. OFF RENT").Range("A" & LrowCompleted + 1)
End If
If Target.Column = 7 And Target.Value = "YES" Then
    Range(Target.Row & ":" & Target.Row).Delete
End If

End Sub