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

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

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

  1. Private Sub Worksheet_Change(ByVal Target As Range)
  2. Dim KeyCells As Range
  3. ' The variable KeyCells contains the cells that will cause an input
  4. 'date and time in next 2 cells to the right when active cell is changed.
  5. Set KeyCells = ActiveSheet.ListObjects("VW_P1_P2").ListColumns("C1 Made Contact?").Range
  6. If Not Application.Intersect(KeyCells, Range(Target.Address)) _
  7. Is Nothing Then
  8. If Target = "Yes" Or Target = "No" Then
  9. ActiveCell.Offset(-1, 1).Value = Format(Now, "mm/dd/yyyy")
  10. ActiveCell.Offset(-1, 2).Value = Format(Now, "hh:mm")
  11. Else
  12. ActiveCell.Offset(-1, 1).ClearContents
  13. ActiveCell.Offset(-1, 2).ClearContents
  14. End If
  15. End If
  16. 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")
  1. Private Sub Worksheet_Change(ByVal Target As Range)
  2. ' The variable KeyCells contains the cells that will cause an input
  3. 'date and time in next 2 cells to the right when active cell is changed.
  4. Dim KeyCells As Range
  5. Set KeyCells = Me.ListObjects("VW_P1_P2").ListColumns("C1 Made Contact?").DataBodyRange
  6. Dim rng As Range
  7. Set rng = Application.Intersect(KeyCells, Target)
  8. If Not rng Is Nothing Then
  9. On Error GoTo SafeExit
  10. Application.EnableEvents = False
  11. Dim cell As Range
  12. For Each cell in rng
  13. If cell.Value = "Yes" Or cell.Value = "No" Then
  14. cell.Offset(-1, 1).Value = Format(Now, "mm/dd/yyyy") ' or just Date
  15. cell.Offset(-1, 2).Value = Format(Now, "hh:mm")
  16. Else
  17. cell.Offset(-1, 1).ClearContents
  18. cell.Offset(-1, 2).ClearContents
  19. End If
  20. Next
  21. End If
  22. SafeExit:
  23. Application.EnableEvents = True
  24. End Sub

编辑

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

  1. With Me.ListObjects("VW_P1_P2")
  2. Dim KeyCells As Range
  3. Set KeyCells = Union(.ListColumns("C1 Made Contact?").DataBodyRange, _
  4. .ListColumns("C2 Made Contact?").DataBodyRange, _
  5. .ListColumns("C3 Made Contact?").DataBodyRange)
  6. End With
展开查看全部

相关问题