允许在worksheet_change事件中插入

时间:2017-07-19 19:30:49

标签: vba excel-vba excel

我创建了一个工作表更改事件,如果更改了列I(添加日期),它会将其插入新工作表并将其删除。

但是,每当我插入一行时,它会自动取出该行并将其插入另一张纸,然后将其删除。如何防止它,只要单元格有一个值,我只能插入工作表更改事件?

我认为我可以通过检查ActiveCell.Value <> ""来进一步嵌套IF语句,但是当单击该单元格时它会发生变化。

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim KeyCells As Range
    Dim LastRowCompleted As Long
    Dim RowToDelete As Long

    RowToDelete = 0
    LastRowCompleted = Sheets("completed").Cells(Sheets("completed").Rows.Count, "A").End(xlUp).Row
    LastRowCompleted = LastRowCompleted + 1 'Next row after last row
    Set KeyCells = Range("I:I")


    If Not Application.Intersect(KeyCells, Range(Target.Address)) Is Nothing Then
    Application.EnableEvents = False
        'Cut and Paste Row
        Target.EntireRow.Copy Sheets("completed").Range(LastRowCompleted & ":" & LastRowCompleted)
        'Mark to delete row
        RowToDelete = Target.EntireRow.Row

    Call DeleteRow(RowToDelete)
    Application.EnableEvents = True

    End If



End Sub

Sub DeleteRow(Row As Long)
    If Row > 0 Then
        Rows(Row).EntireRow.Delete Shift:=xlUp
    End If
End Sub

1 个答案:

答案 0 :(得分:2)

这样的事情:

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim KeyCells As Range

    Set KeyCells = Application.Intersect(Range("I:I"), Target)

    If Not KeyCells Is Nothing Then
        If KeyCells.Cells.Count > 1 Then Exit Sub '<<<<<<<
        If KeyCells.Value <> "" Then
            Application.EnableEvents = False
            With Target.EntireRow
                .Copy Sheets("completed").Cells(Rows.Count, 1).End(xlUp).Offset(1, 0)
                .Delete
            End With
            Application.EnableEvents = True
        End If
    End If

End Sub

请注意,用户可以一次更改多行,但您的代码无法处理:如果您尝试将多单元格区域的值与单个值进行比较运行时错误(因为您尝试将数组与单个值进行比较)