gpt4 book ai didi

vba - 删除行时触发 Excel Worksheet_Change 事件

转载 作者:行者123 更新时间:2023-12-04 20:58:03 26 4
gpt4 key购买 nike

我有一个带有一些 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

有人熟悉这个问题吗?

最佳答案

您可以对 Range Target 进行一些测试, 避免执行代码
(与 Goto 或更确切地说 Exit Sub ):

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

  • 您可以在 Sub 的开头使用这些测试或使用 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

    关于vba - 删除行时触发 Excel Worksheet_Change 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42666036/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com