excel 如何在活动单元格符合条件时删除右侧2个单元格的内容

nuypyhwy  于 2022-11-18  发布在  其他
关注(0)|答案(1)|浏览(520)

我写了下面的代码,如果活动单元格= 'yes'或'no',就在右边的单元格中输入日期。这部分代码工作得很好,但由于某种原因,当活动单元格不符合条件时,我希望它清除右边两个单元格的内容。任何建议都将不胜感激。

Private Sub Worksheet_Change(ByVal Target As Range)

Dim KeyCells As Range

' The variable KeyCells contains the cells that will cause an input
'date and time in next 2 cells to the right when active cell is changed.

Set KeyCells = ActiveSheet.ListObjects("VW_P1_P2").ListColumns("C1 Made Contact?").Range

If Not Application.Intersect(KeyCells, Range(Target.Address)) _
       Is Nothing Then

If Target = "Yes" Or Target = "No" Then
    ActiveCell.Offset(-1, 1).Value = Format(Now, "mm/dd/yyyy")
    ActiveCell.Offset(-1, 2).Value = Format(Now, "hh:mm")
Else
    ActiveCell.Offset(-1, 1).ClearContents
    ActiveCell.Offset(-1, 2).ClearContents
End If

End If
End Sub
0aydgbwb

0aydgbwb1#

几个问题/改进:

  • 请使用Me来参照父工作表,而不要使用ActiveSheet
  • 请避免使用ActiveCell,而改用Target来指涉变更的储存格。
  • Range(Target.Address)是多余的。请使用Target
  • 如果Target是一个多单元格区域,则不能将其与"Yes""No"进行比较,因此使用循环。
  • 您正在以编程方式更改工作表,因此最佳做法是暂时禁用事件,并在最后重新启用它们。
  • 我建议使用.ListColumns("C1 Made Contact?").DataBodyRange而不是.ListColumns("C1 Made Contact?").Range,这将排除列标题C1 Made Contact
  • 您可以使用Date来代替Format(Now, "mm/dd/yyyy")
Private Sub Worksheet_Change(ByVal Target As Range)
    ' The variable KeyCells contains the cells that will cause an input
    'date and time in next 2 cells to the right when active cell is changed.
    Dim KeyCells As Range
    Set KeyCells = Me.ListObjects("VW_P1_P2").ListColumns("C1 Made Contact?").DataBodyRange

    Dim rng As Range
    Set rng = Application.Intersect(KeyCells, Target)

    If Not rng Is Nothing Then
       On Error GoTo SafeExit
       Application.EnableEvents = False

       Dim cell As Range
       For Each cell in rng
           If cell.Value = "Yes" Or cell.Value = "No" Then
               cell.Offset(-1, 1).Value = Format(Now, "mm/dd/yyyy") ' or just Date
               cell.Offset(-1, 2).Value = Format(Now, "hh:mm")
           Else
               cell.Offset(-1, 1).ClearContents
               cell.Offset(-1, 2).ClearContents
           End If
       Next
    End If

SafeExit:
    Application.EnableEvents = True
End Sub

编辑

如果KeyCells是表中的多个列,则可以使用Union

With Me.ListObjects("VW_P1_P2")
   Dim KeyCells As Range
   Set KeyCells = Union(.ListColumns("C1 Made Contact?").DataBodyRange, _
                        .ListColumns("C2 Made Contact?").DataBodyRange, _
                        .ListColumns("C3 Made Contact?").DataBodyRange)
End With

相关问题