【问题标题】:VBA: Why Worksheet Change Event only firing single cells?VBA:为什么工作表更改事件只触发单个单元格?
【发布时间】:2020-12-06 23:30:01
【问题描述】:

如果对任何列逐个单元格进行更改,代码工作正常,但是,如果我一起更改了超过 1 个单元格,则更改不会反映,有人知道为什么吗?

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("Data!O:O")) Is Nothing Then                  
        Target.Offset(0, 14) = Now
    ElseIf Not Intersect(Target, Range("Data!F:F")) Is Nothing Then
        If IsEmpty(Target.Value) = False Then
            Target.Offset(0, 21) = Target.Value
        ElseIf IsEmpty(Target.Value) = True Then
            Target.Offset(0, 21) = Target.Offset(0, -1).Value
        End If
    ElseIf Not Intersect(Target, Range("Data!H:H")) Is Nothing Then
        If IsEmpty(Target.Value) = False Then
            Target.Offset(0, 20) = Target.Value
        ElseIf IsEmpty(Target.Value) = True Then
            Target.Offset(0, 20) = Target.Offset(0, -1).Value
        End If
    End If
End Sub

【问题讨论】:

  • 更改还是选择??如何一次更改多个单元格的值? (当您选择一个范围时,只会更改左上角的单元格)。我还会检查什么是目标范围值调试并在问题中分享,因为如果更改的范围不在目标范围内,那将是调查的起点:)
  • @rustyBucketBay 如何一次更改多个单元格的值? - 复制/粘贴
  • IsEmpty(Target.Value) 不适用于多单元格目标范围
  • @chrisneilsen 我也试过 "" / = "" 但也没有用。我相信 GSerg 已经通过考虑 (isempty / = "") 的循环解决了这个问题。

标签: excel vba


【解决方案1】:

这是 O 列的小演示。如果列中的任何单元格或单元格发生变化,则日期将记录在相邻单元格中:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim RangeOfInterest As Range, Intersection As Range, cell As Range
    
    Set RangeOfInterest = Range("O:O")
    Set Intersection = Intersect(Target, RangeOfInterest)
    
    If Intersection Is Nothing Then Exit Sub
    
    Application.EnableEvents = False
        For Each cell In Intersection
            cell.Offset(0, 1).Value = Date
        Next cell
    Application.EnableEvents = True
End Sub

请注意,我们会遍历 O 列中所有更改的单元格。

编辑#1:

正如GSerg 指出的那样,在这种情况下不需要循环:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim RangeOfInterest As Range, Intersection As Range, cell As Range
    
    Set RangeOfInterest = Range("O:O")
    Set Intersection = Intersect(Target, RangeOfInterest)
    
    If Intersection Is Nothing Then Exit Sub
    
    Application.EnableEvents = False
            Intersection.Offset(0, 1).Value = Date
    Application.EnableEvents = True
End Sub

【讨论】:

  • Note we loop - 但我们不必这样做。 Intersection.Offset(0, 1).Value = Date.
  • @Zatary 查看我的EDIT#1
猜你喜欢
  • 2017-07-04
  • 1970-01-01
  • 2013-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-20
  • 1970-01-01
相关资源
最近更新 更多