删除行时Excel Worksheet_change事件触发



我有一个带有vba代码的Excel工作表

所有效果都很好,但是当我删除一排高于该特定单元格的行时,它会自动更改日期到今天。

这是我用来自动更改单元格的代码:

Private Sub Worksheet_Change(ByVal Target As Range)
Dim WorkRng As Range
Dim Rng As Range
Dim xOffsetColumn As Integer
Set WorkRng = Intersect(Application.Sheets("Example").Range("H10: H306, M10: M306, R10: R306, W10: W306, AB10: AB306, AG10: AG306"), Target)
xOffsetColumn = 1
If Not WorkRng Is Nothing Then
    Application.EnableEvents = False
    For Each Rng In WorkRng
        If Not VBA.IsEmpty(Rng.Value) Then
        Sheets("Example").Unprotect
            Rng.Offset(0, xOffsetColumn).Value = Now
            Rng.Offset(0, xOffsetColumn).NumberFormat = "dd-mm-yyyy"
        Sheets("Example").Protect
        Else
            Rng.Offset(0, xOffsetColumn).ClearContents
        End If
    Next
    Application.EnableEvents = True
End If
End Sub

有人熟悉这个问题吗?

您可以在范围Target上进行一些测试,以避免执行代码
(使用GotoExit Sub):

  • Target.Cells.Count > 1
  • Target.Rows.Count > 1
  • Target.Columns.Count > 1

您可以在子开始时或使用If Not WorkRng Is Nothing Then

使用这些测试

,您的代码可能是:

Private Sub Worksheet_Change(ByVal Target As Range)
Dim WorkRng As Range
Dim Rng As Range
Dim xOffsetColumn As Integer
If Target.Columns.Count > 1 Then Exit Sub
Set WorkRng = Intersect(Application.Sheets("Example").Range("H10: H306, M10: M306, R10: R306, W10: W306, AB10: AB306, AG10: AG306"), Target)
xOffsetColumn = 1
If Not WorkRng Is Nothing Then
    Application.EnableEvents = False
    For Each Rng In WorkRng
        If Not VBA.IsEmpty(Rng.Value) Then
        Sheets("Example").Unprotect
            Rng.Offset(0, xOffsetColumn).Value = Now
            Rng.Offset(0, xOffsetColumn).NumberFormat = "dd-mm-yyyy"
        Sheets("Example").Protect
        Else
            Rng.Offset(0, xOffsetColumn).ClearContents
        End If
    Next
    Application.EnableEvents = True
End If
End Sub

相关内容

  • 没有找到相关文章

最新更新